Vuex(二)——关于store
一、总览
Vuex 应用的核心就是 store(仓库)。
"store" 包含着应用中大部分的状态(state)。
二、Vuex 和单纯全局对象的不同
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutations。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
三、一个例子
1 <div id="app"> 2 <p>{{ count }}</p> 3 <p> 4 <button @click="increment">+</button> 5 <button @click="decrement">-</button> 6 </p> 7 </div>
1 // make sure to call Vue.use(Vuex) if using a module system 2 3 const store = new Vuex.Store({ 4 state: { 5 count: 0 6 }, 7 mutations: { 8 increment: state => state.count++, 9 decrement: state => state.count-- 10 } 11 }) 12 13 const app = new Vue({ 14 el: '#app', 15 computed: { 16 count () { 17 return store.state.count 18 } 19 }, 20 methods: { 21 increment () { 22 store.commit('increment') 23 }, 24 decrement () { 25 store.commit('decrement') 26 } 27 } 28 })
结果为: