Vuex
是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式厂镇,其store
管理多個(gè)組件共享狀態(tài)
一诀拭、安裝
npm install vuex --save
二疫向、使用
在項(xiàng)目src
下新建store
文件夾吹缔,然后創(chuàng)建index.js
商佑,import
所需的模塊,Vue.use()
使用插件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
實(shí)例化Vuex
中的Store
對象
const store = new Vuex.Store({
state: { //類似 vue實(shí)例對象 的 data
name:"張三"
},
mutactions: { //類似 vue實(shí)例對象 的 methods
getname(state[,params]) { //后面可接收傳過來的參數(shù)
console.log(state.name) //輸出'張三'
}
},
getters: { //類似 vue實(shí)例對象 的 computed
name11(state) {
return state.name + '11'
},
fullname(state,getters) { //不接受傳參厢塘,若要傳參請使用callback
return getters.name11 + 'fullname' //getters.name11返回的數(shù)據(jù)進(jìn)行加工
}
},
actions: { //存放執(zhí)行異步操作的函數(shù)
getdata(context[,params]) { //context 即 store對象 茶没,可傳參
settimeout(()=>{ //異步操作
context.commit('getname') //調(diào)用管理的mutactions函數(shù)
},1000)
}
},
modules: { //將管理的狀態(tài)模塊化
moduleA: {
state: {},
mutactions: {
},
getters: {
foo(state,getters,rootState,rootGetters) {
}
},
...//與store結(jié)構(gòu)相同
}
}
})
最后,向外暴露store
對象
export default store
在主文件main.js
中的vue實(shí)例
上進(jìn)行掛載,掛載后在.vue
文件中通過使用this.$store
來獲取vuex
實(shí)例對象store
//main.js
import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
調(diào)用store的資源
- 調(diào)用
store
中mutactions
的函數(shù)晚碾,需要使用this.$store.commit('函數(shù)名'[,參數(shù)])
或者this.$store.commit({type:'函數(shù)名',key:value})
(后者的方式mutactions
中函數(shù)的第二參數(shù)是payload
對象) - 調(diào)用
store
中actions
的函數(shù)抓半,需要使用this.$store.dispatch('函數(shù)名')
- 調(diào)用
store
中modules
的狀態(tài)(state
數(shù)據(jù)),需要使用this.$store.模塊名
來獲取module
中state
對象 - 調(diào)用
store
中modules
的函數(shù)與普通調(diào)用函數(shù)的方法一樣
注:
模塊中函數(shù)名和store
的函數(shù)名最好不要一樣格嘁,如果同名會(huì)調(diào)用store
的函數(shù)
部分抽離
-
store
中的actions
笛求、getters
、mutactions
可以直接在store文件夾
下創(chuàng)建對應(yīng)的.js
文件并暴露 -
modules
可以創(chuàng)建modules文件夾
,再創(chuàng)建對應(yīng)的.js
文件糕簿,模塊化能更好的進(jìn)行管理