Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式
個人理解:就是在項(xiàng)目中可以對在state中定義的變量侣肄,不同的組件之間可以互相使用及修改的目的
npm
npm install vuex --save
Yarn
yarn add vuex
創(chuàng)建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
Store狀態(tài)管理中有2個方法 mutations 和 actions
2個方法都能管理改變state中的值,actions 可以異步操作
在外部引用這個state
需要在 計算屬性中獲取state 的值 通過 this.$store.state.值得名稱
state需要在 computed 取值
Computed:{
Abc(){
Return this.$store.state.值得名稱
}
}
在div中 直接應(yīng)用{{Abc}} 即可獲取state中的值
<div id="app">
<div> {{Abc}} </div>
</div>
如果需要在該組件中對其值 進(jìn)行改變 需要通過以下方法來操作實(shí)現(xiàn)state值得更改
image.png
如果沒有提前預(yù)設(shè)vuex 模塊咏闪,
使用commit 出發(fā) muations 的方法,
this.$store.commit(“方法名”)
使用dispatch觸發(fā)actions 的方法僧免,
this.$store.dispatch(“方法名”)
輔助函數(shù) mapstate 來獲取多個狀態(tài)使用 需要
Import {mapState} from ‘Vuex’
Computed:mapState({
使用方式1
Abc:‘state中定義的名字’
使用方式2
Abc:state=>state.定義的名字
使用方式3
Abc(){
Return this.$store.state.count
}
})
直接在div中通過{{Abc}}來獲取值
是不是很簡單呢
【隨筆】