VUEX
Vuex:是一個集中式狀態(tài)管理工具,相當于react中的 redux
1) 主要解決的問題:大中型項目中復(fù)雜組件通訊問題
2) vuex操作流程:
dispatch commit
vue組件---------------->actions------------>mutations------->state-------->vue組件更新
3)vuex的重要概念:
state:要保存的狀態(tài)
mutations:是最終改變狀態(tài)的方法集,mutations中的代碼是同步執(zhí)行的
actions:
4)使用步驟:
第一步:先安裝vuex
npm install vuex --save
第二步:在src創(chuàng)建一個store目錄,用來存放vuex相關(guān)文件
第三步:在store目錄先創(chuàng)建一個index.js文件,做為vuex入口文件
第四步:在store目錄的index.js中,寫入下面的內(nèi)容
//引入vuex,vue
import Vuex from 'vuex';
import Vue from 'vue';
//讓vue識別vuex
Vue.use(Vuex);
//存儲狀態(tài)
const state={
userinfo:{
username:'張三',
age:20,
token:'1001'
}
}
//將vuex暴露出去
export default new Vuex.Store({
state
});
第五步:在main.js中引入store,并在new Vue中注冊
//引入vuex
import store from './store';
new Vue({
.......
store,
........
});
第六步:如何獲取和設(shè)置數(shù)據(jù)
獲?。涸趯?yīng)組件的computed中處理
即: this.$store.state來獲取
設(shè)置/修改數(shù)據(jù):通過commit到mutations來修改state
如何提高vuex的使用體驗:
1.優(yōu)化state寫法
import {matpState} from 'vuex'
在計算屬性中添加下面的內(nèi)容:
computed:{
//組件的計算屬性
str() {
return "hello"+this.msg
},
//vuex的數(shù)據(jù)
...mapState({
address:'address',
userinfo:'userinfo'
})
}
}
2.優(yōu)化actions,mutations
import { mapState,mapActions,mapMutations } from 'vuex';
...mapActions(['gomodify','aa','bb']),
...mapMutations(['setValue']),
3.隔離vuex各部分,提高可維護性