转 理解vuex -- vue的状态管理模式

转自:http://www.javashuo.com/article/p-xihakfxh-eh.htmljavascript

vuex是什么?

先引用vuex官网的话:css

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

状态管理模式集中式存储管理 一听就很高大上,蛮吓人的。在我看来 vuex 就是把须要共享的变量所有存储在一个对象里面,而后将这个对象放在顶层组件中供其余组件使用。这么说吧,将vue想做是一个js文件、组件是函数,那么vuex就是一个全局变量,只是这个“全局变量”包含了一些特定的规则而已。html

在vue的组件化开发中,常常会遇到须要将当前组件的状态传递给其余组件。父子组件通讯时,咱们一般会采用 props + emit 这种方式。但当通讯双方不是父子组件甚至压根不存在相关联系,或者一个状态须要共享给多个组件时,就会很是麻烦,数据也会至关难维护,这对咱们开发来说就很不友好。vuex 这个时候就很实用,不过在使用vuex以后也带来了更多的概念和框架,需慎重!vue

vuex里面都有些什么内容?

Talk is cheap,Show me the code. 先来一段代码间隔下这么多的文字:java

 
const store = new Vuex.Store({
    state: { name: 'weish', age: 22 }, getters: { personInfo(state) { return `My name is ${state.name}, I am ${state.age}`; } } mutations: { SET_AGE(state, age) { commit(age, age); } }, actions: { nameAsyn({commit}) { setTimeout(() => { commit('SET_AGE', 18); }, 1000); } }, modules: { a: modulesA } }

这个就是最基本也是完整的vuex代码;vuex 包含有五个基本的对象:vuex

  • state:存储状态。也就是变量;
  • getters:派生状态。也就是set、get中的get,有两个可选参数:state、getters分别能够获取state中的变量和其余的getters。外部调用方式:store.getters.personInfo()。就和vue的computed差很少;
  • mutations:提交状态修改。也就是set、get中的set,这是vuex中惟一修改state的方式,但不支持异步操做。第一个参数默认是state。外部调用方式:store.commit('SET_AGE', 18)。和vue中的methods相似。
  • actions:和mutations相似。不过actions支持异步操做。第一个参数默认是和store具备相同参数属性的对象。外部调用方式:store.dispatch('nameAsyn')
  • modules:store的子模块,内容就至关因而store的一个实例。调用方式和前面介绍的类似,只是要加上当前子模块名,如:store.a.getters.xxx()

vue-cli中使用vuex的方式

通常来说,咱们都会采用vue-cli来进行实际的开发,在vue-cli中,开发和调用方式稍微不一样。vue-cli

 
├── index.html
├── main.js ├── components └── store ├── index.js # 咱们组装模块并导出 store 的地方 ├── state.js # 跟级别的 state ├── getters.js # 跟级别的 getter ├── mutation-types.js # 根级别的mutations名称(官方推荐mutions方法名使用大写) ├── mutations.js # 根级别的 mutation ├── actions.js # 根级别的 action └── modules ├── m1.js # 模块1 └── m2.js # 模块2

state.js示例:segmentfault

 
const state = { name: 'weish', age: 22 }; export default state;

getters.js示例(咱们通常使用getters来获取state的状态,而不是直接使用state):app

 
export const name = (state) => { return state.name; } export const age = (state) => { return state.age } export const other = (state) => { return `My name is ${state.name}, I am ${state.age}.`; }

mutation-type.js示例(咱们会将全部mutations的函数名放在这个文件里):框架

 
export const SET_NAME = 'SET_NAME'; export const SET_AGE = 'SET_AGE';

mutations.js示例:

 
import * as types from './mutation-type.js'; export default { [types.SET_NAME](state, name) { state.name = name; }, [types.SET_AGE](state, age) { state.age = age; } };

actions.js示例(异步操做、多个commit时):

 
import * as types from './mutation-type.js'; export default { nameAsyn({commit}, {age, name}) { commit(types.SET_NAME, name); commit(types.SET_AGE, age); } };

modules--m1.js示例(若是不是很复杂的应用,通常来说是不会分模块的):

 
export default { state: {}, getters: {}, mutations: {}, actions: {} };

index.js示例(组装vuex):

 
import vue from 'vue'; import vuex from 'vuex'; import state from './state.js'; import * as getters from './getters.js'; import mutations from './mutations.js'; import actions from './actions.js'; import m1 from './modules/m1.js'; import m2 from './modules/m2.js'; import createLogger from 'vuex/dist/logger'; // 修改日志 vue.use(vuex); const debug = process.env.NODE_ENV !== 'production'; // 开发环境中为true,不然为false export default new vuex.Store({ state, getters, mutations, actions, modules: { m1, m2 }, plugins: debug ? [createLogger()] : [] // 开发环境下显示vuex的状态修改 });

最后将store实例挂载到main.js里面的vue上去就好了

 
import store from './store/index.js'; new Vue({ el: '#app', store, render: h => h(App) });

在vue组件中使用时,咱们一般会使用mapGettersmapActionsmapMutations,而后就能够按照vue调用methods和computed的方式去调用这些变量或函数,示例以下:

 
import {mapGetters, mapMutations, mapActions} from 'vuex'; /* 只写组件中的script部分 */ export default { computed: { ...mapGetters([ name, age ]) }, methods: { ...mapMutations({ setName: 'SET_NAME', setAge: 'SET_AGE' }), ...mapActions([ nameAsyn ]) } };
相关文章
相关标签/搜索