Vuex是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式,其store管理多個組件共享狀態(tài)
一、安裝
npm install vuex --save
二、使用
在項目src下新建store文件夾,然后創(chuàng)建index.js,import所需的模塊,Vue.use()使用插件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
實例化Vuex中的Store對象
const store = new Vuex.Store({
state: { //類似 vue實例對象 的 data
name:"張三"
},
mutactions: { //類似 vue實例對象 的 methods
getname(state[,params]) { //后面可接收傳過來的參數(shù)
console.log(state.name) //輸出'張三'
}
},
getters: { //類似 vue實例對象 的 computed
name11(state) {
return state.name + '11'
},
fullname(state,getters) { //不接受傳參,若要傳參請使用callback
return getters.name11 + 'fullname' //getters.name11返回的數(shù)據(jù)進行加工
}
},
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實例上進行掛載,掛載后在.vue文件中通過使用this.$store來獲取vuex實例對象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ù)名最好不要一樣,如果同名會調(diào)用store的函數(shù)
部分抽離
-
store中的actions、getters、mutactions可以直接在store文件夾下創(chuàng)建對應(yīng)的.js文件并暴露 -
modules可以創(chuàng)建modules文件夾,再創(chuàng)建對應(yīng)的.js文件,模塊化能更好的進行管理