一、概念
在 Vue 中实现集中式状态(数据)管理的 Vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理,也是一种组件间通信的方式,适用于任意组件间通信。使用情景:
多个组件依赖同一状态。
来自不同组件的行为需要变更同一状态。
二、工作原理
![vuex原理图]()
三、环境搭建
npm i vuex
若使用 vue2,应指定 vuex 安装版本npm i vuex@3
在 src 目录下创建 store 目录,并在 store 目录下新建index.js
文件
index.js 内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex);
const action = { fn(context, value) { context.commit("mutation中对应的函数名", value); }, };
const mutations = { fn(state, value) { console.log(state.dataName); console.log(value); }, };
const state = { dataName: value, }; export default new Vuex.Store({ action, mutations, state, });
|
在 main.js 中引入
1 2 3 4
| import store from "./store"; new Vue({ store: store, });
|
调用
1 2 3
| this.$store.dispatch("action中函数名", value); this.$store.commit("mutations中函数名", value); this.$store.state.dataName;
|
若没有网络请求或其他业务逻辑,组件可越过 actions,即不写 dispatch,直接写 commit。
来源:https://www.bilibili.com/video/BV1Zy4y1K7SH?p=105
四、getter 配置项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex);
const action = { fn(context, value) { context.commit("mutation中对应的函数名", value); }, };
const mutations = { fn(state, value) { console.log(state.dataName); console.log(value); }, };
const state = { dataName: value, };
const getters = { fn(state) { return state.dataName * 10; }, }; export default new Vuex.Store({ action, mutations, state, getters, });
|
五、四个 map
(一)、mapState
mapState 用于生成函数与 state 中数据的映射。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import {mapState} from 'vuex' computed:{ ...mapState({ 自定义函数名:'state中数据名', fn:'dataName' }) }
computed:{ fn(){ return this.$store.state.dataName; } }
computed:{ ...mapState(['函数名','fn']) }
|
(二)、mapMutations
会生成this.$store.commit()
,与 mapState 写法相同。
1 2 3 4 5
| ...mapMutations({自定义函数名:'mutations中方法名',fn:'fn'})
fn(value){ this.$store.commit('fn',value) }
|
(三)、mapActions
生成this.$store.dispatch()
,使用方法相同
(四)、mapGetters
生成this.$store.getters.getter中方法名
,使用方法相同
六、vuex 模块化编程
将不同功能的 vuex 模块进行分类,以便于维护。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const person = { namespaced: true, actions: {}, mutations: {}, state: {}, getters: {}, }; const count = { namespaced: true, actions: {}, mutations: {}, state: {}, getters: {}, }; export default new Vuex.Store({ modules: { person, count, }, });
|
获取 state 中的数据:
1 2
| ...mapState('person',['person中的state数据名']) ...mapState('count',['count中的state数据名'])
|
若没有开启命名空间:
1 2
| ...mapState(['person中的state数据名']) {{person.state.person中的state数据名}}
|
commit:
1
| this.$store.commit("person/fn", value);
|