console
// 初始化 vuex 实例(可以将这个放到其他文件里面去))
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => state.count++,
},
actions: {
// context 对象的使用跟 store 对象的使用类似
increment (context) {
// 直接可以 commit(原来是this.$store.commit)
context.commit('increment')
},
// { commit }就是 context
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 5000)
}
}
})
// 初始化子组件
const Counter = {
template: `<p>{{ count }}</p>`,
computed: {
count () {
return this.$store.state.count
}
}
}
// 初始化 vue 实例
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<button @click="increment">+</button>
<button @click="Aincrement">+(async)</button>
<counter></counter>
</div>
`
,
methods: {
increment () {
store.dispatch('increment')
},
Aincrement () {
store.dispatch('incrementAsync')
},
}
})
<div id="app" class="app">
</div>
.app{
background-color:#ffffff
}