一、安裝:
npm install vuex --save
二、在src目錄下新建一個名為store的文件夾,為方便引入并在store里新建一個index.js,內(nèi)容如下:
import Vue from'vue';
import Vuex from'vuex';
import test from './modules/test';
Vue.use(Vuex);
const store =new Vuex.Store({
???? state,
? ? ? getters,
????? actions,
????? mutations
? ? modules: { test },
});
export default store;
三、在 main.js里面引入store,然后再全局注冊,這樣就可以在任何一個組件里面使用this.$store了:
import store from'./store' //引入store
new Vue({
el:'#app',
router,
store,//使用store
template:'<App/>',
components: { App }
})
四、在store下新建modules文件夾,并新建測試用test.js,內(nèi)容:
const test = {
? ? state: {
? ? ? ? msg: '原始數(shù)據(jù)'
? ? },
const getters = {????? //實(shí)時監(jiān)聽state值的變化(最新狀態(tài))
?????? getMsg(state) {??????????
???????????? return? state.msg
?????? }
};
? ? mutations: {
? ? ? ? SET_MSG(state, msg) {
? ? ? ? ? ? state.msg=msg;
? ? ? ? },
? }
};
const actions={
?? setMsg(context,msg){
???????? context.commit('SET_MSG',msg);
?? }
}
export default test;
五、最后就是在組件使用了:
1、this.$store.dispatch('setMsg','測試數(shù)據(jù)')??? //設(shè)置msg的值
2、this.$store.getters.getMsg?? //獲取msg的值