Vue2从0到1(三):Vuex的使用

上两篇讲了:

环境的搭建用webpack打包vueVue-router的使用

下面讲一下:

9.vuex的应用

安装vuex

npm install vuex --save
9.1基本用法:

新建store.js文件:

        import Vue from 'vue';
        import Vuex from 'vuex';

        Vue.use(Vuex)
        //创建Store实例
        const store = new Vuex.Store({
            // 存储状态值
            state: {
                count:1
        },
            // 状态值的改变方法,操作状态值
            // 提交mutations是更改Vuex状态的唯一方法
            mutations: {
                increment(state){
                    state.count++;
                },
                decrement(state){
                    state.count--;
                }
        },
            // 在store中定义getters(可以认为是store的计算属性)。Getters接收state作为其第一个函数
            getters: {
                
        },
            actions: {
                
        }
        })
        // 要改变状态值只能通过提交mutations来完成
        export default store;

在main.js里面注入store;

    ...
    //引入store
    import store from './store.js'
    ...
    const app = new Vue({
        router,
        store
    }).$mount('#main')

新建count.vue文件,并新建路由指向count组件参照vue-router的使用
count.vue文件:

    
    
    

效果图:
Vue2从0到1(三):Vuex的使用_第1张图片


9.2用Module拆分state

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter

新建moduleA.js,moduleB.js

moduleA

moduleB

并修改store.js:

...
import moduleA from './moduleA';
import moduleB from './moduleB';
...
Vue.use(Vuex)
//创建Store实例
const store = new Vuex.Store({
    modules:{
        moduleA, moduleB //es6的写法,合并模块
    }
})
...

在组件里面想访问到state需要用到

    $store.state.moduleA.count
    $store.state.moduleB.Name

效果图:
Vue2从0到1(三):Vuex的使用_第2张图片
mutations里面修改state的方法依然不变

下章将讲用nodejs+koa2搭建后台,提供数据,以及Vuex的异步操作

以上代码代码亲测可用,托管在github上面,欢迎star

你可能感兴趣的:(webpack,vuex,vue.js,javascript)