用來管理狀態(tài)办斑,共享數(shù)據(jù)扩灯,在各個組件之間管理外部狀態(tài)
第一步:項目安裝vuex插件
npm i vuex
第二步:引入vuex牵署,并通過use方法使用它
import Vuex from 'vuex'
Vue.use(Vuex)
第三步: 創(chuàng)建狀態(tài)倉庫
//創(chuàng)建狀態(tài)倉庫疚颊,注意第二個Store是大寫的不能改狈孔,,state也是不能改
var store = new Vuex.Store({
state:{ //在state對象建立需要數(shù)據(jù)
XXX:xxx
}
})
第四步:在main.js注入Vue實例當中
new Vue({
el: '#app',
router,
store, //注入store,當鍵名(key)和值(value)名字一樣可以這樣縮寫
components: { App },
template: '<App/>'
})
第五步:通過this.$sore.state.XXX拿到全局狀態(tài)
computed:{
getOutterNum:function(){
return this.$store.state.XXX
}
}
七斑胜、Vuex的相關(guān)操作
vuex狀態(tài)管理的流程
view——->actions—–>mutations—–>state——->view
一绍申、
方法一、更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation
const store = new Vuex.Store({ //定義了store
state:{
num:88
},
mutations:{ //定義狀態(tài)改變函數(shù) 相當于methods方法
increase:function(state){
state.num++
},
decrease:function(state){
state.num--
//1、store.commit('save') 定義了的store利用commit在mutations調(diào)用自身mutations其他函數(shù)
}
//2传惠、save(){...}
}
})
在其他組件中利用commit來觸發(fā)mutations函數(shù)
methods:{
sadd:function(){
this.$store.commit('increase') //commit方法里面是mutations定義的函數(shù)名
}
},
this.$store.commit('increase',xxx)
xxx
表示傳入?yún)?shù)靶累,如果需要傳入多個參數(shù)顾患,將xxx
表示成對象{xxx1:'',xxx2:''}
方式傳入暇检,在對象內(nèi)構(gòu)成多個需要傳入?yún)?shù)。
方法二:
利用actions中對mucations進行操作深寥,間接對state進行修改
mutations:{
increase:function(state){
state.num++
},
decrease:function(state){
state.num--
}
},
actions:{ //actions中只能對mucations進行操作
//context為上下文對象
decreaseActions:function(context){
context.commit('decrease') //decrease方法是mucations中定義的方法
}
}
})
利用dispatch來觸發(fā)actions函數(shù)
saddActions:function(){
//dispatch方法里面是actions定義的函數(shù)名
this.$store.dispatch('decreaseActions')
}
mucations和actions兩者之間區(qū)別
1攘乒、傳遞參數(shù)不一樣,前者傳遞是state惋鹅,后者傳遞是context则酝。
2、調(diào)用的方式不一樣闰集,前者靠this.$store.commit('xxx')
觸發(fā)沽讹,后者靠this.$store.dispatch('xxx')
觸發(fā)。
3武鲁、actions可以包含異步操作爽雄,但是mutation只能包含同步操作
actions:{
decreaseActions:function(context){
setTimeout(() => { //延時一秒的異步操作
context.commit('decrease')
}, 1000);
}
}
二、getters是vuex中的一個屬性沐鼠,主要作用于vue中的計算屬性(computed)類似挚瘟,用來存放一些經(jīng)過修改的數(shù)值
getters:{
getNum:function(state){
return state.num>0? state.num:0
}
}
在調(diào)用getters中的內(nèi)容是使用$store.getters.函數(shù)名進行調(diào)用
computed:{
getParentNum:function(){
return this.$store.getters.getNum //getNum是getter里面定義方法
}
}
總結(jié):在工程化項目中,vuex所有內(nèi)容建議和routers一樣饲梭,在src中建立一個state文件夾>index.js刽沾,將vuex內(nèi)容寫在index.js中,再導(dǎo)出到main.js中排拷。