Vuex是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式沃于。它采用集中式存儲管理應用的所有組件的狀態(tài),并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化蹦玫。
這個狀態(tài)自管理應用包含以下幾個部分:
state: 驅(qū)動應用的數(shù)據(jù)源
view: 以聲明方式將state映射到視圖
actions: 響應在view上的用戶輸入導致的狀態(tài)變化
1.安裝
npm install vuex --save
or
yarn add vuex
2.使用
每一個 Vuex
應用的核心就是 store
(倉庫)歉备。 "store"
基本上就是一個容器谈竿,它包含著你的應用中大部分的狀態(tài) (state)
。 Vuex
和單純的全局對象有以下兩點不同:
-
Vuex
的狀態(tài)存儲是響應式的沮尿。當Vue
組件從store
中讀取狀態(tài)的時候丛塌,若store
中的狀態(tài)發(fā)生變化,那么相應的組件也會相應地得到高效更新畜疾。 - 你不能直接改變
store
中的狀態(tài)赴邻。改變store
中的狀態(tài)的唯一途徑就是顯式地提交(commit)mutations
。這樣使得我們可以方便地跟蹤每一個狀態(tài)的變化啡捶,從而讓我們能夠?qū)崿F(xiàn)一些工具幫助我們更好地了解我們的應用姥敛。
3.注冊
在src下創(chuàng)建Vuex文件夾, 在文件夾中創(chuàng)建store.js 導入并注冊
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
在main.js 中要進行引入
import store from './vuex/store'
new Vue({
el: '#app',
router,
// 把 store 對象提供給 "store" 選項,這可以把 store 的實例注入所有的子組件
store,
template: '<App/>',
components: { App }
})
4.項目中調(diào)用
在store文件中創(chuàng)建并導出
export default new Vuex.store ({
// 保存初始狀態(tài)的地方
state: {
count: 0
},
// 定義方法改變狀態(tài)的地方
mutations : {
// state 狀態(tài) num 傳進來的參數(shù)
increment:(state, num) =>{
console.log(state)
state.count = num
}
}
})
5.調(diào)用狀態(tài)
this.$store.state.count
// 可以在計算屬性computed調(diào)用
computed: {
src() {
return this.$store.state.count
}
},
6.修改狀態(tài)
this.$store.commit('increment', 10)
// 以載荷形式分發(fā)
this.$store.commit({
type: 'increment',
amount: 10
})
// 以對象形式分發(fā)
this.$store.commit('increment', {
amount: 10
})
7. action
Action
類似于mutation
瞎暑,不同在于:
Action
提交的是mutation
彤敛,而不是直接變更狀態(tài)。
Action
可以包含任意異步操作了赌。
// 異步操作
actions: {
increments (context, num) {
context.commit('increment', num)
}
}
Action
函數(shù)接受一個與 store
實例具有相同方法和屬性的 context
對象墨榄,因此你可以調(diào)用 context.commit
提交一個 mutation
,或者通過 context.state
和 context.getters
來獲取 state
和 getters
揍拆。
8. 觸發(fā)action
this.$store.dispatch('increments', 50)
9. Module
由于使用單一狀態(tài)樹渠概,應用的所有狀態(tài)會集中到一個比較大的對象。當應用變得非常復雜時嫂拴,store 對象就有可能變得相當臃腫播揪。
為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)筒狠。每個模塊擁有自己的 state猪狈、mutation、action辩恼、getter雇庙、甚至是嵌套子模塊——從上至下進行同樣方式的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)