vuex状态管理插件
-
什么是vuex
vue状态管理插件,集中式存储管理应用的所有组件的状态,某个组件改变了状态数据其它组件跟着发生变化。 -
核心
-
Vue Components:Vue组件。HTML页面上,负责接收用户操作等交互行为,执行dispatch方法触发对应action进行回应。
-
dispatch:操作行为触发方法,是唯一能执行action的方法。
-
actions:操作行为处理模块,由组件中的$store.dispatch(‘action 名称’, data1)来触发。然后由commit()来触发mutation的调用 , 间接更新 state。负责处理Vue Components接收到的所有交互行为。包含同步/异步操作,支持多个同名方法,按照注册的顺序依次触发。向后台API请求的操作就在这个模块中进行,包括触发其他action以及提交mutation的操作。该模块提供了Promise的封装,以支持action的链式触发。
-
commit:状态改变提交操作方法。对mutation进行提交,是唯一能执行mutation的方法。
-
mutations:状态改变操作方法,由actions中的commit(‘mutation 名称’)来触发。是Vuex修改state的唯一推荐方法。该方法只能进行同步操作,且方法名只能全局唯一。操作之中会有一些hook暴露出来,以进行state的监控等。
-
state:页面状态管理容器对象。集中存储Vue components中data对象的零散数据,全局唯一,以进行统一的状态管理。页面显示所需的数据从该对象中进行读取,利用Vue的细粒度数据响应机制来进行高效的状态更新。
-
getters:state对象读取方法。图中没有单独列出该模块,应该被包含在了render中,Vue Components通过该方法读取全局state对象。
-
-
案例
- 下载vuex插件 npm i vuex -S
- 创建store.js模块文件
import Vuex from 'vuex'; import Vue from 'vue'; Vue.use(Vuex); let store = new Vuex.Store({ state: { count:0 }, mutations:{ reduce(state){ state.count++; } }, actions:{ plus({commit,state}){ commit('reduce'); } }, getters:{ getCount(state){ return state.count; } } }) export default store;
- 在入口文件app.js集成vuex
import store from './store.js' Vue.protoType.$store = store;// 所有vue实例都可以调用$store new Vue({ el:'#app', store, render: C=>C(App) })
- 组件中使用
```javascript methods:{ onChangeClick(){ // 修改vuex中状态数据 this.$store.dispatch('plus'); // state状态管理器中count加一 this.total = this.$store.getters.getCount; // 获取state状态count值 }, onMinusClick(){ this.$store.dispatch('minus'); } } ```