Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。
vue組件通過dispatch方法觸發(fā)Actions動作,然后Actions通過commit方法來觸發(fā)Mutations,Mutations通過mutate方法來更改State狀態(tài),然后State狀態(tài)再用render方法渲染到組件上。
Actions執(zhí)行異步操作(比如后臺調(diào)用API),Mutations執(zhí)行同步操作。

<h3>1. Vuex的安裝</h3>
通過package.json將Vuex引入,通過 npm install安裝。
<h3>2. Vuex的實例</h3>
<h5>2.1 項目引入Vuex</h5>
在main.js文件中引入Vuex,然后調(diào)用use方法使用,接著實例化一個store,將Vuex.Store傳入store中,各種參數(shù)就在store中寫。
import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store({
})
<h5>2.2 Vuex的實現(xiàn)</h5>
demo實現(xiàn)效果:父組件中定義一個總數(shù)totalPrice,在子組件(page1)通過加減兩個按鈕,能對父組件的totalPrice實現(xiàn)增加,減少操作。(page1加減按鈕一次操作數(shù)值為5)
在App.vue中
我們定義totalPrice 計算屬性在頁面顯示,totalPrice的值通過Vuex下的store.getters中的getTotal計算出來。
<div>{{totalPrice}}</div>
export default {
computed: {
totalPrice () {
return this.$store.getters.getTotal
}
}
在page1子組件中
定義addOne和minusOne方法,用兩個按鈕承載。按下按鈕會通過dispatch方法為increase,decrease這兩個actions動作傳入data中的price(即this.price)
<div>
{{'名稱:' + name}}
{{'價格:' + price}}
<button @click="addOne">加一</button>
<button @click="minusOne">減一</button>
</div>
export default{
data () {
return {
name: '蘋果',
price: 5
}
},
methods: {
addOne () {
this.$store.dispatch('increase', this.price)
},
minusOne () {
this.$store.dispatch('decrease', this.price)
}
}
}
在main.js中
①我們通過state來定義totalPrice這個變量。
②this.price傳入actions中的increase和decrease后,actions 函數(shù)傳入了context和price兩個參數(shù),price來接收this.price, 而context 對象與 store 實例具有相同方法和屬性的,因此我們可以調(diào)用 context.commit 提交一個 mutation,把price提交過去。
③更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation。我們也設置兩個參數(shù),第一個參數(shù)就是狀態(tài)state,第二個參數(shù)就是price,我們通過price來接收commit過來的price,傳入state是為了使用state.totalPrice這個回調(diào)函數(shù),來對state下的totalPrice進行操作。
④我們在getters中定義getTotal這個方法,傳入state,返回state.totalPrice,返回的值能被App.vue中的totalPrice直接調(diào)用。
let store = new Vuex.Store({
state: {
totalPrice: 0
},
getters: {
getTotal (state) {
return state.totalPrice
}
},
mutations: {
increment (state, price) {
state.totalPrice += price
},
decrement (state, price) {
state.totalPrice -= price
}
},
actions: {
increase (context, price) {
context.commit('increment', price)
},
decrease (context, price) {
context.commit('decrement', price)
},
}
})
把store放在這里,全局使用(跟vue-router一樣)
const app = new Vue({
el: '#app',
store,
render: h => h(App)
})


這樣我們就完成了Vuex的整個生命周期。