码迷,mamicode.com
首页 > 其他好文 > 详细

vuex 初体验

时间:2019-07-30 09:22:45      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:官方   esc   water   定义   vue   new   操作   性方面   user   

以前一直想学下vuex 但是一直没有学进去,今天无聊看看vuex ,没想到竟然如此之简单,可能看react-redux 看懵了,现在忘了react-redux 再一看vuex真的是眼前一亮,不得不说,起码易用性方面vue真的是甩react 好几条街。
首先贴上官方文档,
https://vuex.vuejs.org/guide/modules.html

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

技术图片

根据提示 运行 npm run serve 熟悉的界面就来了:

技术图片

这些没必要说了,下面进入正题,其实已经自动整合了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=)

vuex 初体验

标签:官方   esc   water   定义   vue   new   操作   性方面   user   

原文地址:https://blog.51cto.com/13496570/2424660

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!