状态管理模式Vuex
Vuex
-
定义
- Vuex 是集中式存储管理应用的所有组件的状态(数据)
-
作用
- 可实现任意组件之间的通讯
-
特点
- 当不同的组件需要对同一个状态进行读写时,或者复用的状态较多
- 能够保持数据和页面是响应式的
- 便于开发和后期数据维护
安装
cnpm install --save vuex
创建 /store/index.js 文件
// 创建 /store/index.js 文件
import Vue from 'vue' //引入Vue
import Vuex from 'vuex' //引入Vuex
Vue.use(Vuex) //应用
export default new Vuex.Store({
actions:{}, //接受用户的事件
mutations:{}, //操作state中的数据
state:{}, //存放共享的数据
})
// main.js
import store from './store/index.js'
new Vue({
el:"#app",
render: h => h(App),
store:store
})
- 实现对
store数据的count累加和累减- 读取
store的state
- 读取
<h1>当前的计数:{{ $store.state.count }}</h1>
- 操作
store的state
methods: {
// 累加
add() {
this.$store.commit("ADD", this.sum); //同步操作
// this.$store.dispatch("add", this.sum); //异步操作
},
// 累减
reduce() {
this.$store.commit("REDUCE", this.sum); //同步操作
// this.$store.dispatch("reduce", this.sum); //异步操作
},
},
store配置actions和mutations
//接受用户的事件
actions: {
add(context, value) {
context.commit('ADD', value);
},
reduce(context, value) {
setTimeout(() => {
context.commit('REDUCE', value);
}, 1000);
},
},
//操作state中的数据
mutations: {
ADD(state, value) {
state.count += value;
},
REDUCE(state, value) {
state.count -= value;
},
},
-
注意
actions能够提供dispatch方法实现异步操作mutations必须是同步函数state只能通过mutations配置的方法去修改

浙公网安备 33010602011771号