vuex
by Irene Tang
HTML
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@1.4.1/lib/index.js"></script>
<script src="//unpkg.com/vuex@2.0.0"></script>
<script id="foo" type="x-template">
<div>
<p>this count of foo is {{ fooCount }}</p>
<el-button @click="addBar">add bar's count</el-button>
</div>
</script>
<script id="bar" type="x-template">
<div>
<p>this count of bar is {{ barCount }}</p>
<el-button @click="addFoo">add foo's count</el-button>
</div>
</script>
<div id="parent">
<foo></foo>
<hr>
<bar></bar>
</div>
CSS
@import url("//unpkg.com/element-ui@1.4.1/lib/theme-default/index.css");
JavaScript
const store = new Vuex.Store({
state: {
fooCount: 0,
barCount: 0
},
getters: {
fooCount: state => state.fooCount,
barCount: state => state.barCount
},
actions: {
addBar ({ commit, state }, param) {
commit('addBar', param)
},
addFoo ({ commit }, param) {
commit('addFoo', param)
}
},
mutations: {
addBar (state, num) {
state.barCount += num
},
addFoo (state, num) {
state.fooCount += num
}
}
})
var Foo = {
template: '#foo',
computed: {
fooCount () {
return this.$store.getters.fooCount
}
},
methods: {
addBar () {
this.$store.dispatch('addBar', 2)
}
}
}
var Bar = {
template: '#bar',
computed: {
barCount () {
return this.$store.getters.barCount
}
},
methods: {
addFoo () {
this.$store.dispatch('addFoo', 1)
}
}
}
new Vue({
el: '#parent',
components: {
Foo, Bar
},
store
})