vuex状态管理主要包含四个概念 mapState,mapMutations,mapGetters,mapActions。
编写vuex文件夹下面的store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const state = { count:1, cc:111 } const mutations={ add(state){ state.count+=1; }, reduce(state){ state.count-=1; } } const getters = { count: function (state) { return state.count += 100; } } const actions = { addAction(context) { // context.commit('add'); setTimeout(() => { context.commit('add') }, 1000); }, reduceAction(context) { setTimeout(() => { context.commit('reduce') }, 1000); } }; export default new Vuex.Store({ state, mutations, getters, actions });
项目main.js中引入vuex
import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import './style/element-variables.scss' import store from './vuex/store' import './config/axios.js' import 'babel-polyfill' Vue.config.productionTip = false Vue.use(ElementUI) /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
组件页面代码如下
<template> <div class="page"> <h1>{{msg}}</h1> <div> <h1>{{cc}}</h1> <h1>{{count}}</h1> <el-button @click="add">add++</el-button> <el-button @click="reduce">reduce--</el-button> <el-button @click="addAction">addAction++</el-button> <el-button @click="reduceAction">reduceAction--</el-button> </div> </div> </template> <script> import { mapState, mapMutations, mapGetters, mapActions } from "vuex"; export default { data() { return { msg: 'vuex demo', } }, computed: mapState({ count: state => state.count, cc: state => state.cc, }),//此处mapStat函数形式科直接替代mapGetters处理数据 //mapState两种形式 // computed:{ // ...mapState([ // 'count', // 'cc', // ]), // ...mapGetters([ // 'count', // ]), // },//此处对象扩展需在vuex文件用getters处理数据 methods: { ...mapMutations(["add", "reduce"]), ...mapActions(["addAction", "reduceAction"]), } } </script> <style lang="scss"> </style>
附上实际开发项目目录
在vue的组件化实际项目开发中,我们经常会遇到需要将当前组件的状态传递给其他组件。父子组件通信时,我们通常会采用 props + emit 这种方式。但当通信双方不是父子组件甚至压根不存在相关联系,或者一个状态需要共享给多个组件时,就会非常麻烦,数据也会相当难维护,这对我们开发来讲就很不友好。vuex 这个时候就很实用。