Vuex

什么是Vuex及Vuex的优缺点

Vuex是专为Vue.js应用程序开发的状态管理模式。比如一个简单的Vue计数应用:

new Vue({
  // state
  data () {
    return {
      count: 0
    }
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
})

这个状态自管理应用包含以下三部分:
· state,驱动应用的数据源
· view,以声明方式将state映射到视图
· actions,响应在view上的用户输入导致的状态变化
对于如下图所示的单向数据流:

image.png

当遇到多个组件共享状态的时候,其简洁性很容易被破坏:
· 多个视图依赖于同一状态
· 来自不同视图的行为需要变更同一状态
所以,可以把组件的共享状态抽取出来,以一个全局单例模式管理,在这种模式下,组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或触发行为。Vuex便由此而生。

Vuex的优缺点

Vuex可以帮助管理共享状态,对开发大型单页应用带来了方便。但如果要开发的应用足够简单,Vuex可能就显得相对繁琐冗余,不适合使用。

Vuex五大属性

Vuex的五大属性分别是:state、getter、mutation、action、module
根据我个人的理解,可以把Vuex与Vue组件进行对照记忆:
**state => 基本数据 => data
getters => 从基本数据派生的数据 => computed
mutations => 提交更改数据的方法,同步! => 同步methods
actions => 像一个装饰器,包裹mutations,使之可以异步。 => 异步调用methods
modules => 模块化Vuex

1. state

2. getter

3. mutation

4. action

5. module

module是考虑到使用单一状态树,当所有状态集中到一个比较大的对象时,如果应用变得非常复杂, 那么store对象就可能变得相当臃肿,不便于开发与维护。
Vuex允许将store分割成多个模块(module),每个模块都拥有自己的state、mutation、action、getter,甚至能嵌套子模块(module)。
注意:moduleX的声明必须在store之前。

const moduleA = {
    state: {
        count: 3
    },
    mutations: {
        increment(state) {
            state.count++
        }
    },
    getters: {
      sumWithRootCount (state, getters, rootState) {
        return state.count + rootState.count
     }
    },
    actions: {
        incrementIfOddOnRootSum({state, commit, rootState}){
            if((state.count + rootState.count) % 2 === 1){
                commit('increment')
            }
        }
    }
}

const moduleB = {
    state: {
        count: 8
    },
    mutations: {
        login() {}
    },
    getters: {
        login() {}
    },
    actions: {
        login() {}
    }
}

const store = new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB
    },
    state: {
        count: 2
    },
    mutations: {
        increment(state) {
            state.count++
        }
    },
    actions: {

    },
    getters: {

    }
})

new Vue({
    el: '#app',
    store,
    data: {

    },
    computed: {

    }
});

对于模块内部的mutation和getter,接收的第一个参数是模块的局部state,如moduleA的mutation与getter。
对于模块内部的action,局部state通过'context.state暴露出来,根节点状态则通过context.rootState暴露出来。如moduleA中的action。 对于模块内部的getter,根节点state则作为第三个参数暴露出来。如moduleA中的getter。 **命名空间** 默认情况下,模块内部的action、mutation、getter是注册在全局命名空间的,即假如你定义的moduleA与store都有increment()的mutation属性,那当你执行:store.commit('increment')`的时候,会将store与其子模块里mutation的increment方法一起调用。如:

console.log(store.state.a.count); // 3
console.log(store.state.count); // 2
store.commit('increment');
console.log(store.state.a.count); // 4
console.log(store.state.count); // 3

如果你希望定义的模块有更高的封装度和复用性,可以通过加入namespaced: true的方式使其成为带命名空间的模块。当模块被注册后,其所有的getter、action与mutation都会自动根据模块注册的路径调整命名。
例如给moduleA添加namespaced: true,则执行store.commit('increment')时会自动跳过moduleA。此时:

const moduleA = {
    namespaced: true
......
......
}

console.log(store.state.a.count); // 3
console.log(store.state.count); // 2
store.commit('increment');
console.log(store.state.a.count); // 3
console.log(store.state.count); // 3

此时若想执行moduleA的increment,则要这样写:store.commit('a/increment'),这样便只执行moduleA中的increment。
若moduleA嵌套moduleC,则在不声明moduleC的namespaced情况下,其继承父模块moduleA的命名空间。即:

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          state: { ... },
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,

          state: { ... },
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

在带命名空间的模块内访问全局内容
对于getter,会将rootState与rootGetters作为第三与第四参数传入:

    getters: {
        someGetter (state, getters, rootState, rootGetters) {
            rootState.count;
            state.count;
            
            getters.someOtherGetter;
            rootGetters.someOtherGetter;
        }
    },

对于mutation与action,将(root: true}作为第三参数传给dispatch或commit即可:

    actions: {
        someAction({ dispatch, commit, getters, rootGetters }) {
            getters.someGetter;
            rootGetters.someGetter;
            
            dispatch('someOtherAction'); // 不传第三参数,则从自身查找
            dispatch('someOtherAction', null, { root: true }); // 传入第三参数,则从父模块查找
            
            commit('someMutation'); // 与上同理
            commit('someMutation', null, { root: true });
        }
    }

那么对于mapState、mapGetters、mapMutations、mapActions这些函数来绑定带命名空间的模块时,直接写可能有点繁琐:

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。上面的例子可以简化为:

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}

模块动态注册
你可以在store创建之后,动态地用store.registerModule方法给store创建模块:

// 注册模块 `myModule`
store.registerModule('myModule', {
  // ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

之后就能通过store,state.myModulestore.state.nested.myModule来访问模块的状态。你也可以使用 store.unregisterModule(moduleName)来动态卸载模块。但需要注意,你不可以卸载store声明时的模块,即静态模块。
保留state
在注册新module时,如果你想保留过去的state,例如从服务器渲染的应用保留state,可以通过preserveState选项将其归档store.registerModule('a', module, { preserveState: true })
当你设置 preserveState: true 时,该模块会被注册,action、mutation 和 getter 会被添加到 store 中,但是 state 不会。这里假设 store 的 state 已经包含了这个 module 的 state 并且你不希望将其覆写。
模块重用
在实际开发中可能会有一个store中多次注册同一个模块,或者多个store注册同一个模块的需求,此时module被引用调用一次,其state就可能被重写,导致store或模块间数据互相污染。(类似于Vue组件内的data会遇到同样的问题)
解决办法也类似,就是使用一个函数来声明模块状态:

const MyReusableModule = {
  state () {
    return {
      foo: 'bar'
    }
  },
  // mutation, action 和 getter 等等...
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容