如下针对 vuex 1.x 及 某些0.x 版本html
官方文档有个很是简单的 tutorial, 我这里在精简一下,代码大概以下:vue
htmlvuex
<h3>Count is {{ counterValue }}</h3> <div> <button @click="increment">Increment +1</button> <button @click="decrement">Decrement -1</button> </div>
jsthis
new Vue({ el: 'body', store: new Vuex.Store({ state: { count: 0 }, mutations: { INCREMENT: function(state, amount) { state.count = state.count + amount }, DECREMENT: function(state, amount) { state.count = state.count - amount } } }), vuex: { getters: { counterValue: function(state) { return state.count } }, actions: { increment: function({ dispatch, state }){ dispatch('INCREMENT', 1) }, decrement: function({ dispatch, state }){ dispatch('DECREMENT', 1) } } } })
预览
http://jsbin.com/cofupo/edit?...spa
若是上面代码不用 vuex 实现的话会很是简单,html 代码不变,js 更新以下:code
new Vue({ el: 'body', data: { counterValue: 0 }, methods: { increment: function(){ this.counterValue = this.counterValue + 1; }, decrement: function(){ this.counterValue = this.counterValue - 1; }, } })
经过上面的代码对比, vuex 把应用的数据和修改数据的方法放在了一个 store
对象里面统一管理, 对数据的获取和操做则分别经过 vm 新增建的配置属性 vuex 的 getters 和 actions 来进行。htm