vuex first experience

Had always wanted to learn but has not studied under vuex go in, take a look at vuex bored today, did not think so simple, you may see the react-redux look ignorant, now forgotten react-redux Made vuex really shines , have to say, at least, ease of use vue really good a few blocks thrown react.
First paste official documents,
https://vuex.vuejs.org/guide/modules.html

 新建项目就不多说了,用vue-cli ,在新建项目的选项上选择了typescript 和class 类的方式,这种形式也和react 的class 方式是很像的,然后一直下一步下一步,项目就给你自动创建成功了,很吊有没有。

vuex first experience

Follow the prompts to run npm run serve a familiar interface to come:

vuex first experience

这些没必要说了,下面进入正题,其实已经自动整合了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 are some filtering operations on the state of, if you want to change the state on the implementation of the method store.commit

The second parameter is a parameter passed.

Are now defined on a store files of all state, when the project is getting bigger if it is this way, then the store must be more and more, is there any way to optimize it? Modules of course that is
the official website examples

Create a new store named 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=)

Guess you like

Origin blog.51cto.com/13496570/2424660