Skip to content

Commit a3cc347

Browse files
author
starkwang
committed
add mutations
1 parent 50877df commit a3cc347

File tree

3 files changed

+48
-4
lines changed

3 files changed

+48
-4
lines changed

src/components/Stark.vue

+13-3
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
<template>
22
<div :class="$style.hello">
3-
<!-- <h1>{{ num }}</h1> -->
3+
<h1>{{ count }}</h1>
4+
<button @click="add">add</button>
45
</div>
56
</template>
67

78
<script>
8-
99
import stark from './stark.css'
1010
export default {
1111
name: 'HelloWorld',
12+
computed: {
13+
count() {
14+
return this.$stark.state.count
15+
},
16+
},
1217
created() {
13-
console.log('stark',this.$stark.state)
18+
console.log('stark', this.$stark.state)
19+
},
20+
methods: {
21+
add(){
22+
this.$stark.commit('increment')
23+
}
1424
}
1525
}
1626
</script>

src/stark/index.js

+6
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,11 @@ const debug = process.env.NODE_ENV !== 'production'
88

99
export default new Vuex.Stark({
1010
state,
11+
mutations: {
12+
increment(state) {
13+
state.count = state.count + 10
14+
console.log('当前状态为', state.count)
15+
},
16+
},
1117
strict: debug,
1218
})

src/starkx/stark.js

+29-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,41 @@
11
import applyMixin from './mixin'
2-
2+
import Vue from 'vue'
33
export class Stark {
44
constructor(options = {}) {
55
console.log('options', options)
66
this.options = options
7+
this.mutations = {}
8+
const { commit } = this
9+
this.commit = type => {
10+
return commit.call(this, type)
11+
}
12+
forEachValue(options.mutations, (mutationFn, mutationName) => {
13+
registerMutation(this, mutationName, mutationFn)
14+
})
15+
// 数据响应式
16+
this._vm = new Vue({
17+
data: {
18+
state: options.state,
19+
},
20+
})
721
}
822
get state() {
923
return this.options.state
1024
}
25+
26+
commit(type) {
27+
this.mutations[type]()
28+
}
29+
}
30+
31+
function registerMutation(store, mutationName, mutationFn) {
32+
store.mutations[mutationName] = () => {
33+
mutationFn.call(store, store.state)
34+
}
35+
}
36+
37+
function forEachValue(obj, fn) {
38+
Object.keys(obj).forEach(key => fn(obj[key], key))
1139
}
1240

1341
export function install(Vue) {

0 commit comments

Comments
 (0)