应用四:Vue之VUEX状态管理

 

(注:本文适用于有一定Vue基础或开发经验的读者,文章就知识点的讲解不一定全面,但却是开发过程中很实用的)

 

概念:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

 

应用场景Vue多个组件之间需要共享数据或状态。

 

Vuex有几个核心概念:StateGetterMutationActionModule

 

State:存储状态数据

Getter:从状态数据派生数据,相当于State的计算属性。

Mutation:存储用于同步更改状态数据的方法,默认传入的参数为state。

Action:存储用于异步更改状态数据,但不是直接更改,而是通过触发Mutation方法实现,默认参数为context

ModuleVuex模块化。

 

它们之间的交互关系如下图(来源于官方文档)所示:

接下来先看一个Vuex应用的简单实例,新建store.js文件并添加如下代码:

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    name: ''
  },
  getters: {
    getName(state) {
      return 'hello ' + state.name;
    }
  },
  mutations: {
    mutationSetName(state, name) {
      state.name = name;
    }
  },
  actions: {
    actionSetName(context, name) {
      setTimeout(() => {
        context.commit('mutationSetName', name);
      }, 1000);
    }
  }
});
export default store;

 

然后将该store实例注入到所有子组件,方法如下:

import store from './store.js';
new Vue({
  el: '#app',
  router,
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { App },
  template: '<App/>'
});

 

接下来就可以在vue的各个子组件中通过下面的方式访问vuex对象实例。

this.$store.state.name;
this.$store.getters.getName;
this.$store.commit('mutationSetName', 'zhangsan');
this.$store.dispatch('actionSetName', 'lisi');

 

或者也可以通过辅助函数的方式访问,

1、需要在应用的子组件中引入辅助函数

import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

2、在计算属性computed中注入state和getters

computed: {
    ...mapState({
      // 把 `this.name` 映射为 `this.$store.state.name`
      name: state => state.name
    }),
    ...mapGetters({
      // 把 `this.getName` 映射为 `this.$store.getters.getName`
      getName: getName
    })
}

3、在methods中注入mutations和actions

methods: {
    ...mapMutations([
      // 将 `this.mutationSetName()` 映射为 `this.$store.commit('mutationSetName')`
      'mutationSetName'
    ]),
    ...mapActions([
      // 将 `this.actionSetName()` 映射为 `this.$store.dispatch('actionSetName')`
      'actionSetName'
    ])
}

 

模块化

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store对象就有可能变得相当臃肿。

为了解决以上问题,Vuex允许我们将store分割成模块。每个模块拥有自己的stategettermutationaction、甚至是嵌套子模块-从上到下进行同样的分割。

 

下面新建moduleA和moduleB两个js文件,分别添加如下代码:

const moduleA = {
  namespaced: true,
  state: {
    name: ''
  },
  getters: {},
  mutations: {},
  actions: {}
}
export default moduleA;
const moduleB = {
  namespaced: true,
  state: {
    name: ''
  },
  getters: {},
  mutations: {},
  actions: {}
}
export default moduleB;

 

然后新建store.js文件并引入上述两个模块文件,代码如下:

import moduleA from './moduleA.js';
import moduleB from './moduleB.js';
const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
export default store;

 

其中a、b为自定义的模块别名,接下来按前文同样的方式将store对象注入vue

访问方式如下:

this.$store.state.a.name // -> moduleA 的状态name
this.$store.state.b.name // -> moduleB 的状态name

辅助函数访问方式和前文所讲区别不大,只是多了模块名称字段:

computed: {
    ...mapState('a', {
      name: state => state.name
    }),
    ...mapState('b', {
      name: state => state.name
    })
}

其他几个对象gettermutationaction的访问方式类似,都要加上模块名称字段。  

 

注意:

1、是否使用Vuex要根据项目的实际规模,在简单的应用中使用 Vuex 可能会显得繁琐冗余;对于中大型的单页应用,Vuex在状态管理方面才是最好的选择。

2、Vuex和单纯的全局对象不同。Vuex 的状态存储是响应式的,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

3、不能直接改变 store 中的状态改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation,这样有利于跟踪每一个状态的变化。

 

以上就是vuex的基础用法,更多详细的说明请查阅官方文档:https://vuex.vuejs.org/zh/。 

 

posted @ 2019-05-29 20:41  风岳轩  阅读(4279)  评论(0编辑  收藏  举报