記vuex的使用

一、安裝:

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的值


★到這里就已經(jīng)是能夠?qū)崿F(xiàn)大部分vuex的使用了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容