vuex 初體驗

以前一直想學下vuex 但是一直沒有學進去,今天無聊看看vuex ,沒想到竟然如此之簡單,可能看react-redux 看懵了,現在忘了react-redux 再一看vuex真的是眼前一亮,不得不說,起碼易用性方面vue真的是甩react 好幾條街。
首先貼上官方文檔,
https://vuex.vuejs.org/guide/modules.html

 新建項目就不多說了,用vue-cli ,在新建項目的選項上選擇了typescript 和class 類的方式,這種形式也和react 的class 方式是很像的,然後一直下一步下一步,項目就給你自動創建成功了,很吊有沒有。

vuex 初體驗

根據提示 運行 npm run serve 熟悉的界面就來了:

vuex 初體驗

這些沒必要說了,下面進入正題,其實已經自動整合了vuex 
並且創建了 store.ts
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
    name: 'Hello Word',
    count: 1,
    users: [
        { name: '×××', age: 18 },
        { name: '小劉', age: 18 },
        { name: '小王', age: 11 },
        { name: '小張', age: 18 },
        { name: '小鵬', age: 18 },
        { name: '小強', age: 19 },
        { name: '小子', age: 20 },
    ]
},
mutations: {
    increment(state, payload) {
        // mutate state
        state.count += payload.count;
    },
},
getters: {
    getAges: (state) => {
        return state.users.filter(user => {
            return user.age > 18;
        });
    }
},
actions: {

},
});
(稍微添加了點東西);

那麼我們在頁面上怎麼用他呢?
只需要引入 store.ts 然後 store.state 就可以獲取state了
以HelloWorld.vue 爲例

getters 是對state的一些過濾操作,如果想要改變state 就執行store.commit 方法

第二個參數是傳遞的參數。

現在都是在一個store文件上定義所有state ,當項目越來越大的時候如果還採用這種方式,那麼store必定越來越大,有沒有什麼辦法優化呢?當然有那就是Modules
官網例子

新建一個store 取名 combineStore.ts:

 import Vue from 'vue';
import Vuex from 'vuex';
const moduleA = {
    state: { name: "moduleA" },
    mutations: {},
    actions: {},
    getters: {}
}

const moduleB = {
    state: { name: "moduleB" },
    mutations: {},
    actions: {}
}

const Combilestore = new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB
    }
})

// store.state.a // -> `moduleA`'s state
// store.state.b // -> `moduleB`'s state

export default Combilestore;
引入組件中就可以用了:

![](https://s1.51cto.com/images/blog/201907/29/d35bcd31ead170e64d6ae3c1bb2c4c25.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

結果:

![](https://s1.51cto.com/images/blog/201907/29/a7d050413fb5120b390f9ee2fc97f2a9.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章