本文整理来自深入Vue3+TypeScript技术栈-coderwhy大神新课,只作为个人笔记记录使用,请大家多支持王红元老师。
推荐先阅读Vuex,掌握Vuex的基本使用之后再看这篇文章。
什么是状态管理
在开发中,我们会的应用程序需要处理各种各样的数据,这些数据需要保存在我们应用程序中的某一个位置,对于这些数据的管理我们就称之为状态管理。
在前面我们是如何管理自己的状态呢?
- 在Vue开发中,我们使用组件化的开发方式,而在组件中我们定义data或者在setup中返回使用的数据,这些数据我们称之为state;
- 在模块template中我们可以使用这些数据,模块最终会被渲染成DOM,我们称之为View;
- 在模块中我们会产生一些行为事件,处理这些行为事件时,有可能会修改state,这些行为事件我们称之为actions;
复杂的状态管理
JavaScript需要管理的状态越来越多,越来越复杂,这些状态包括服务器返回的数据、缓存数据、用户操作产生的数据等等,也包括一些UI的状态,比如某些元素是否被选中,是否显示加载动效,当前分页。
当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏,因为多个视图依赖于同一状态,来自不同视图的行为需要变更同一状态。
我们是否可以通过组件数据的传递来完成呢? 对于一些简单的状态,确实可以通过props的传递或者Provide的方式来共享状态,但是对于复杂的状态管理来说,显然单纯通过传递和共享的方式是不足以解决问题的,比如兄弟组件如何共享数据呢?
Vuex的状态管理
管理不断变化的state本身是非常困难的,因为状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化。当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪。
因此,我们是否可以考虑将组件的内部状态抽离出来,以一个全局单例的方式来管理呢? 在这种模式下,我们的组件树构成了一个巨大的 “视图View”,不管在树的哪个位置,任何组件都能获取状态或者触发行为,通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,我们的代码边会变得更加结构化和易于维护、跟踪。
这就是Vuex背后的基本思想,它借鉴了Flux、Redux、Elm(纯函数语言,redux有借鉴它的思想)。
Vuex有五大核心:State、Getters、Mutations、Actions、Modules,下面我们慢慢讲。
上面流程图大概意思就是:Vue组件通过dispatch触发Actions,然后Actions通过commit触发Mutations,然后Mutations再修改Vuex里面的数据。
Vuex的安装
首先第一步需要安装vuex,我们这里使用的是vuex4.x,安装的时候需要添加 next 指定版本。
npm install vuex@next
创建Store
每一个Vuex应用的核心就是store(仓库),store本质上是一个容器,它包含着你的应用中大部分的状态(state)。
Vuex和单纯的全局对象有什么区别呢?
- Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新。
- 你不能直接改变store中的状态。改变store中的状态的唯一途径就是提交 (commit) mutation,这样使得我们可以方便的跟踪每一个状态的变化,从而让我们能够通过一些工具帮助我们更好的管理应用的状态。
使用步骤:
① 创建Store对象;
② 在app中通过插件安装;
组件中使用store
在组件中使用store,我们按照如下的方式:
- 在模板中使用;
- 在options api中使用,比如computed;
- 在setup中使用;
Vue devtool
vue其实提供了一个devtools,方便我们对组件或者vuex进行调试。我们需要安装beta版本支持vue3,目前是6.0.0 beta15。
有两种常见的安装方式: 方式一:通过chrome的商店; 方式二:手动下载代码,编译、安装;
由于某些原因我们可能不能正常登录Chrome商店,所以可以选择第二种;
手动安装devtool
手动下载代码,编译、安装:
- github.com/vuejs/devto…
- 打开项目,终端执行 yarn install 安装相关的依赖;
- 终端执行 yarn run build 打包,打包好的文件在shell-chrome文件夹里面
- 打开浏览器,点击加载已解压的扩展程序,选择shell-chrome文件夹;
单一状态树
Vuex 使用单一状态树,用一个对象就包含了全部的应用层级的状态,采用的是SSOT,Single Source of Truth,也可以翻译成单一数据源,这也意味着,每个应用将仅仅包含一个 store 实例,单状态树和模块化并不冲突,后面我们会讲到module的概念。
单一状态树的优势也就是单一,如果你的状态信息是保存到多个Store对象中的,那么之后的管理和维护等等都会变得特别困难,所以Vuex也使用了单一状态树来管理应用层级的全部状态。单一状态树能够让我们最直接的方式找到某个状态的片段,而且在之后的维护和调试过程中,也可以非常方便的管理和维护。
Vuex的简单使用
和使用vue-router一样,我们需要创建一个store文件夹,然后在store文件夹里创建一个index.js文件,在index.js文件里面将store对象导出。然后在main.js文件里面使用store。
main.js文件代码如下:
import { createApp } from 'vue'
import App from './App.vue'
//导入创建的store
import store from './store'
//使用store
createApp(App).use(store).mount('#app')
index.js代码如下:
import { createStore } from "vuex"
const store = createStore({
// 保存的数据
// state是个函数,返回一个对象,和data类似
// 以前是个对象,现在我们推荐写成一个函数
state() {
return {
counter: 100,
name: "why",
age: 18,
height: 1.88
}
},
// 对数据进行一些加工
getters: {
doubleCounter(state) {
return state.counter * 2
}
},
//修改数据
mutations: {
increment(state) {
state.counter++
}
}
});
export default store;
使用数据和修改数据:
//使用vuex中的数据
<h2>{{ $store.state.counter }}</h2>
//通过commit调用mutations中的increment方法,从而修改数据
this.$store.commit("increment")
获取组件状态:state
在前面我们已经学习过如何在组件中获取状态了,当然,如果觉得那种方式有点繁琐(表达式过长),我们可以使用计算属性。
但是,如果我们有很多个状态都需要获取话,一个一个写计算属性会很麻烦,我们可以使用mapState辅助函数。
在computed中使用mapState
mapState函数接收一个数组或者对象作为参数,返回值是一个对象,对象里面是一个一个函数,我们使用展开运算符将它与局部计算属性混合。而且如果有命名冲突的情况,我们可以传入对象进行重命名。
<template>
<div>
<h2>Home:{{ $store.state.counter }}</h2>
<h2>Home:{{ sCounter }}</h2>
<h2>Home:{{ sName }}</h2>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
// 原来的计算属性
fullName() {
return "Kobe Bryant"
},
// 其他的计算属性, 从state获取
// 直接传数组
// ...mapState(["counter", "name", "age", "height"])
// 如果有名字冲突,可以传对象
...mapState({
sCounter: state => state.counter,
sName: state => state.name
})
}
}
</script>
<style scoped>
</style>
在setup中使用mapState
在setup中如果我们单个获取状态是非常简单的,通过useStore拿到store后去获取某个状态即可,但是如果我们需要使用 mapState 的功能呢?
<template>
<div>
<h2>Home:{{ $store.state.counter }}</h2>
<hr>
<h2>{{sCounter}}</h2>
<h2>{{counter}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{height}}</h2>
<hr>
</div>
</template>
<script>
import { mapState, useStore } from 'vuex'
import { computed } from 'vue'
export default {
computed: {
fullName: function() {
return "1fdasfdasfad"
},
...mapState(["name", "age"])
},
setup() {
const store = useStore()
// 1. setup中写成计算属性,这也是常用的方法
// 但是写下面三行代码也是很麻烦的,那么我们想在setup中也使用mapState,怎么做呢?
const sCounter = computed(() => store.state.counter)
// const sName = computed(() => store.state.name)
// const sAge = computed(() => store.state.age)
// 下面这种写法是Vuex官方文档里面也没有的
// 2. 我们先用mapState方法拿到如下数据
//返回的是{name: function, age: function, height: function}对象
//这样在setup中我们直接用...解构获取的就是一个一个函数,我们直接展示一个函数肯定不行啊
const storeStateFns = mapState(["counter", "name", "age", "height"])
// 我们需要做如下操作,将 {name: function, age: function, height: function} 转成 {name: ref, age: ref, height: ref},因为computed函数返回的就是ref
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
// 虽然我们使用的是mapState的方式,vue内部还是会通过this.$store.state获取数据,所以我们给它绑定this
// 这时候函数内部的this就是{$store: store}对象,所以现在通过this.$store.state就能获取到数据了
const fn = storeStateFns[fnKey].bind({$store: store})
// 然后将fn用computed包裹一下,这时候就能展示了
storeState[fnKey] = computed(fn)
})
return {
sCounter,
...storeState
}
}
}
</script>
<style scoped>
</style>
默认情况下,在setup中,Vuex并没有提供非常方便的使用mapState的方式,这里我们封装一个useState函数,函数接收的参数就是mapState的参数,返回值是一个对象。
新建useState.js文件,代码如下:
import { computed } from 'vue'
import { mapState, useStore } from 'vuex'
export function useState(mapper) {
// 拿到store对象
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: function}
const storeStateFns = mapState(mapper)
// 对数据进行转换
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return storeState
}
使用useState函数如下:
<template>
<div>
<h2>Home:{{ $store.state.counter }}</h2>
<hr>
<h2>{{counter}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{height}}</h2>
<h2>{{sCounter}}</h2>
<h2>{{sName}}</h2>
<hr>
</div>
</template>
<script>
//导入函数
import { useState } from '../hooks/useState'
export default {
setup() {
// useState可以传数组或者对象,这是因为内部的mapState可以传数组或者对象,返回的东西都是对象
const storeState = useState(["counter", "name", "age", "height"])
const storeState2 = useState({
sCounter: state => state.counter,
sName: state => state.name
})
return {
...storeState,
...storeState2
}
}
}
</script>
<style scoped>
</style>
这样我们就使用useState函数实现了原来computed中的mapState函数的功能。
getters的基本使用
某些属性我们可能需要经过变化后来使用,这个时候可以使用getters,在store中定义方式如下:
getters: {
// 第一个参数是state,第二个参数是getters
totalPrice(state, getters) {
let totalPrice = 0
for (const book of state.books) {
totalPrice += book.count * book.price
}
//getters可以接收第二个参数,从而实现在getters里面访问另外一个getters
return totalPrice * getters.currentDiscount
},
currentDiscount(state) {
return state.discount * 0.9
}
}
使用如下:
<h2>总价值: {{ $store.getters.totalPrice }}</h2>
getters的返回函数
getters是个对象,对象里面是函数,函数除了可以返回一个值之外,还可以返回另一个函数,那么在使用的地方可以调用这个函数,并且传递参数。
getters: {
totalPriceCountGreaterN(state, getters) {
//除了返回一个值,还可以返回一个函数
return function(n) {
let totalPrice = 0
for (const book of state.books) {
if (book.count > n) {
totalPrice += book.count * book.price
}
}
return totalPrice * getters.currentDiscount
}
}
}
使用如下:
<h2>总价值: {{ $store.getters.totalPriceCountGreaterN(3) }}</h2>
getters返回模板字符串
getters: {
// 返回模板字符串
nameInfo(state) {
return `name: ${state.name}`
},
ageInfo(state) {
return `age: ${state.age}`
},
heightInfo(state) {
return `height: ${state.height}`
}
}
mapGetters辅助函数
和state一样,如果我们感觉通过$store.getters.totalPrice获取getters有点麻烦,可以将其写成计算属性(代码如下),但是如果getters特别多,我们一个一个写计算属性也会很麻烦,所以我们需要mapGetters辅助函数。
computed: {
totalPrice() {
return this.$store.getters.totalPrice
}
}
在computed中使用mapGetters
mapGetters和mapState一样,也是接收一个数组或对象,返回一个对象,对象里面是函数。
computed: {
//传入数组,使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters(["nameInfo", "ageInfo", "heightInfo"]),
//传入对象,好处就是可以重命名
...mapGetters({
//这里和mapState的对象写法不一样,mapState的对象写法是传入一个函数,这里直接传入一个字符串就可以
//其实就是直接映射为this.$store.getters.nameInfo
sNameInfo: "nameInfo",
sAgeInfo: "ageInfo"
})
}
使用如下:
<h2>{{ ageInfo }}</h2>
<h2>{{ heightInfo }}</h2>
<h2>{{ sNameInfo }}</h2>
<h2>{{ sAgeInfo }}</h2>
在setup中使用mapGetters
和mapState一样,在setup中我们可以直接将其写成计算属性,这也是常用的写法:
setup() {
const store = useStore()
// 1. setup中写成计算属性,这也是常用的方法
const sCounter = computed(() => store.getters.counter)
// const sName = computed(() => store.getters.name)
// const sAge = computed(() => store.getters.age)
return {
sCounter,
}
}
但是如果属性多了,我们就需要写很多的计算属性,所以在setup中使用mapGetters,我们可以封装一个useGetters函数,新建useGetters.js文件,代码如下:
import { computed } from 'vue'
import { mapGetters, useStore } from 'vuex'
export function useGetters(mapper) {
// 拿到store对象
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: function}
const storeStateFns = mapGetters(mapper)
// 对数据进行转换
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return storeState
}
使用如下:
<template>
<div>
<h2>{{ nameInfo }}</h2>
<h2>{{ ageInfo }}</h2>
<h2>{{ heightInfo }}</h2>
</div>
</template>
<script>
// 导入函数
import { useGetters } from '../hooks/useGetters'
export default {
computed: {
},
setup() {
//使用useGetters函数
const storeGetters = useGetters(["nameInfo", "ageInfo", "heightInfo"])
return {
...storeGetters
}
}
}
</script>
<style scoped>
</style>
封装useState.js和useGetters.js
我们发现useState.js和useGetters.js代码几乎是一样的,所以我们新建useMapper.js文件,重新封装一下,代码如下:
import { computed } from 'vue'
import { useStore } from 'vuex'
//具体是使用mapState还是使用mapGetters我们不清楚,所以让外界传进来mapFn
export function useMapper(mapper, mapFn) {
// 拿到store对象
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: function}
const storeStateFns = mapFn(mapper)
// 对数据进行转换
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return storeState
}
这时候useState.js代码就是:
import { mapState } from 'vuex'
import { useMapper } from './useMapper'
export function useState(mapper) {
return useMapper(mapper, mapState)
}
useGetters.js代码就是:
import { mapGetters } from 'vuex'
import { useMapper } from './useMapper'
export function useGetters (mapper) {
return useMapper(mapper, mapGetters)
}
这时候我们只需要新建一个index.js文件作为统一的出口,下次我们使用的时候直接导入这个文件就行了,代码如下:
import { useGetters } from './useGetters';
import { useState } from './useState';
export {
useGetters,
useState
}
这时候我们导出的就是一个对象,对象里有两个方法,我们拿到这个对象,解构后想使用哪个方法就使用哪个方法就行了。
Mutations基本使用
Mutations定义如下:
mutations: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
// 增加n payload就是传过来的参数
[INCREMENT_N](state, payload) {
state.counter += payload.n
},
addBannerData(state, payload) {
state.banners = payload
}
}
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<!-- 不传参数,直接提交commit -->
<button @click="$store.commit('increment')">+1</button>
<button @click="$store.commit('decrement')">-1</button>
<!-- 传参数 -->
<button @click="addTen">+10</button>
<hr>
</div>
</template>
<script>
export default {
methods: {
addTen() {
// 传入一个参数
// this.$store.commit('incrementN', 10)
// 传入多个参数就写成一个对象
// this.$store.commit('incrementN', {n: 10, name: "why", age: 18})
// 这时候后面的参数就会被传到incrementN函数的第二个参数
// 另外一种提交风格,指定type,参数就放后面,不常用
this.$store.commit({
type: 'incrementN',
n: 10,
name: "why",
age: 18
})
}
}
}
</script>
<style scoped>
</style>
上面代码还有个小问题,就是函数名incrementN容易写错,而且写错之后很难发现,这时候我们可以将函数名incrementN定义成常量。
在store文件夹中新建mutation-types.js文件,代码如下:
export const INCREMENT_N = "increment_n"
定义mutation:
import { INCREMENT_N } from './mutation-types'
[INCREMENT_N](state, payload) {
state.counter += payload.n
}
提交mutation:
import { INCREMENT_N } from '../store/mutation-types'
this.$store.commit(INCREMENT_N, 10)
其实这样也不是最好的,因为如果方法多了,我们就需要导入多个,我们直接定义成对象,其实也是可以的,比如:
const types = {
SET_LOCATION: 'SET_LOCATION', //定位信息
SET_ADDRESS: 'SET_ADDRESS', //地址
ORDER_INFO: 'ORDER_INFO', //订单信息
ADDRESS_INFO: 'ADDRESS_INFO', //选中地址信息
REMARK_INFO: 'REMARK_INFO', //餐具信息 + 订单备注都存在这一个vuex中
};
mapMutations辅助函数
上面代码,直接通过this.$store.commit(INCREMENT_N, 10)调用会很长,封装成一个addTen函数又会多了一个函数,这时候我们可以使用mapMutations辅助函数将我们需要使用的函数映射到methods里面。当我们使用mapMutations映射之后,调用方法,方法内部会调用$store.commit,这样我们就不用写this.$store.commit(INCREMENT_N, 10)这样很长的代码了。
mapMutations也是接收一个数组或对象,返回一个对象,对象里面是函数。
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<!-- 当我们使用mapMutations映射之后,调用方法,方法内部会调用$store.commit -->
<button @click="increment">+1</button>
<button @click="add">+1</button>
<button @click="decrement">-1</button>
<button @click="increment_n({n: 10})">+10</button>
<hr>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
import { INCREMENT_N } from '../store/mutation-types'
export default {
//在methods中使用
methods: {
// 传入数组
...mapMutations(["increment", "decrement", INCREMENT_N]),
// 传入对象,改名字
...mapMutations({
add: "increment"
})
},
setup() {
// 在setup中使用就比mapState和mapGetters简单多了
// 因为返回的就是{increment: function, decrement: function}对象,我们把对象结构之后就是我们需要的方法
const storeMutations = mapMutations(["increment", "decrement", INCREMENT_N])
return {
...storeMutations
}
}
}
</script>
<style scoped>
</style>
Mutation重要原则
一条重要的原则:mutation 必须是同步函数,这是因为devtool工具会记录mutation的日记,每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照,但是在mutation中执行异步操作,就无法追踪到数据的变化,所以Vuex的重要原则中要求 mutation 必须是同步函数。
Actions的基本使用
Actions类似于Mutations,不同在于:
- Action提交的是mutation,而不是直接变更状态;
- Action可以包含任意异步操作;
如果一些网络请求的数据是直接存到Vuex里面,那么网络请求就没必要写到组件中了,直接写到actions中,这样在组件中我们只需要做一次事件派发就行了。
actions: {
// 第一个参数是context,第二个参数是我们调用dispatch传递过来的参数{count: 100}
incrementAction(context, payload) {
console.log(payload)
// 延迟1s
setTimeout(() => {
context.commit('increment')
}, 1000);
},
// Mutations的第一个参数是state
// 对于Actions,context的其他属性,解构出来,可以发现包含state和commit
decrementAction({ commit, dispatch, state, rootState, getters, rootGetters }) {
commit("decrement")
},
//如果一些网络请求的数据是直接存到Vuex里面,那么网络请求就没必要写到组件中了,直接写到actions中即可
getHomeMultidata(context) {
//返回Promise对象,好在then或者catch里面处理其他事情
return new Promise((resolve, reject) => {
axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
//拿到数据后提交commit
context.commit("addBannerData", res.data.data.banner.list)
resolve({name: "coderwhy", age: 18})
}).catch(err => {
reject(err)
})
})
}
}
这里有一个非常重要的参数context,context是一个和store实例均有相同方法和属性的context对象。所以我们可以从其中获取到commit方法来提交一个mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。但是为什么它不是store对象呢?这个等到我们讲Modules时再具体来说。
Actions的分发操作
进行action的分发使用的是 store 上的dispatch函数:
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
<hr>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
increment() {
//分发,携带参数
this.$store.dispatch("incrementAction", {count: 100})
},
decrement() {
//派发风格(对象类型),携带参数
this.$store.dispatch({
type: "decrementAction",
count: 100
})
}
},
mounted() {
//组件挂载完成直接分发操作,获取首页数据
this.$store.dispatch("getHomeMultidata")
},
setup() {
}
}
</script>
<style scoped>
</style>
mapActions辅助函数
和Mutations一样,如果我们不想写this.$store.dispatch("incrementAction", {count: 100})这些代码,可以使用mapActions辅助函数,它也有两种写法:数组类型和对象类型,也是返回一个对象,对象里面是函数。
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<button @click="incrementAction">+1</button>
<button @click="decrementAction">-1</button>
<button @click="add">+1</button>
<button @click="sub">-1</button>
<hr>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
// 在methods中使用
methods: {
...mapActions(["incrementAction", "decrementAction"]),
...mapActions({
add: "incrementAction",
sub: "decrementAction"
})
},
// 在setup中使用,也是简单
setup() {
const actions = mapActions(["incrementAction", "decrementAction"])
const actions2 = mapActions({
add: "incrementAction",
sub: "decrementAction"
})
return {
...actions,
...actions2
}
}
}
</script>
<style scoped>
</style>
Actions的异步操作
Action 通常是异步的,那么如何知道 Action 什么时候结束呢? 我们可以通过让Action返回Promise,在Promise的then中来处理完成后的操作。
actions: {
getHomeMultidata(context) {
//返回Promise对象,好在then或者catch里面处理其他事情
return new Promise((resolve, reject) => {
axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
//拿到数据后提交commit
context.commit("addBannerData", res.data.data.banner.list)
//回调then
resolve({name: "coderwhy", age: 18})
}).catch(err => {
//回调catch
reject(err)
})
})
}
}
<template>
<div>
<h2>当前计数: {{ $store.state.counter }}</h2>
<hr>
<button @click="incrementAction">+1</button>
<button @click="decrementAction">-1</button>
<button @click="add">+1</button>
<button @click="sub">-1</button>
<hr>
</div>
</template>
<script>
import { onMounted } from "vue";
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
onMounted(() => {
// 派发操作
const promise = store.dispatch("getHomeMultidata")
promise.then(res => {
//请求成功的操作
console.log(res)
}).catch(err => {
//请求失败的操作
console.log(err)
})
})
}
}
</script>
<style scoped>
</style>
总结
由于我们使用this.$store.state.counter和this.$store.getters.totalCount
比较麻烦,一个一个映射到计算属性又会写很多,所以我们使用mapState和mapGetters将他们映射到计算属性中。
由于通过this.$store.commit(increment_n, 10) 和this.$store.dispatch("incrementAction", {count: 100})
调用方法比较麻烦,所以我们使用mapMutations和mapActions将它们映射到方法中。
Module的基本使用
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module),每个模块拥有自己的 state、getter、mutation、action、甚至是嵌套子模块。
在store文件夹中新建modules文件夹和index.js文件,modules文件夹用于存放模块js文件。
home.js文件如下:
const homeModule = {
state() {
return {
homeCounter: 100
}
},
getters: {
},
mutations: {
},
actions: {
}
}
export default homeModule
user.js文件如下:
const userModule = {
state() {
return {
userCounter: 10
}
},
getters: {
},
mutations: {
},
actions: {
}
}
export default userModule
index.js文件代码如下:
import { createStore } from "vuex"
// 导入某个模块相关的状态管理
import home from './modules/home'
import user from './modules/user'
const store = createStore({
// 保存的数据
state() {
return {
rootCounter: 100
}
},
// 对数据进行一些加工
getters: {
doubleRootCounter(state) {
return state.rootCounter * 2
}
},
//修改数据
mutations: {
increment(state) {
state.rootCounter++
}
},
// 状态管理,模块划分
modules: {
home,
user
}
});
export default store;
使用如下:
<h2>root:{{ $store.state.rootCounter }}</h2>
<h2>home:{{ $store.state.home.homeCounter }}</h2>
<h2>user:{{ $store.state.user.userCounter }}</h2>
module的命名空间
先说两个问题:
问题一:比如index.js里面的mutations内有一个increment方法,home.js里面的mutations内也有一个increment方法,当我们提交commit触发increment方法的时候,这两个increment方法都会被调用。这里有个问题,因为有时候我们不想两个increment方法都被调用。
问题二:当我们在home.js里面的getters里面定义一个doubleHomeCounter,无论你是通过$store.state.home.doubleHomeCounter还是$store.state.home.getters.doubleHomeCounter还是$store.getters.home.doubleHomeCounter其实都是拿不到doubleHomeCounter,这是因为默认做了个合并,我们需要通过$store.getters.doubleHomeCounter才能拿到doubleHomeCounter。这里有个问题,因为我们不知道doubleHomeCounter到底是哪个模块里面的。
这是因为,默认情况下,模块内部的mutation和action和Getters仍然是注册在全局的命名空间中的,会进行合并,这样使得多个模块能够对同一个mutation或action作出响应。
如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块,这样当模块被注册后,它的所有 getter、mutation 及 action 都会自动根据模块注册的路径调整命名。
当我们加上namespaced: true后,每个模块就是独立的了,我们就要指定是哪个模块,如下:
<template>
<div>
<!-- 获取根的rootCounter -->
<h2>root:{{ $store.state.rootCounter }}</h2>
<!-- 获取home的homeCounter -->
<h2>home:{{ $store.state.home.homeCounter }}</h2>
<!-- 获取user的userCounter -->
<h2>user:{{ $store.state.user.userCounter }}</h2>
<hr>
<!-- 获取home的getters里面的doubleHomeCounter -->
<h2>{{ $store.getters["home/doubleHomeCounter"] }}</h2>
<button @click="homeIncrement">home+1</button>
<button @click="homeIncrementAction">home+1</button>
</div>
</template>
<script>
export default {
methods: {
homeIncrement() {
// 指定home模块的commit
this.$store.commit("home/increment")
},
homeIncrementAction() {
// 指定home模块的dispatch
this.$store.dispatch("home/incrementAction")
}
}
}
</script>
<style scoped>
</style>
子module的一些参数
对于模块内部的 getter 和 mutation,接收的第一个参数是模块的局部状态对象也就是这个模块的state。同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState,其他参数如下:
home.js文件代码如下:
const homeModule = {
//开启命名空间
namespaced: true,
state() {
return {
homeCounter: 100
}
},
getters: {
// 前面我们讲了在根里面的getters里面有state和getters两个参数, 其实在子模块的getters里面还有更多的参数
// state就是上面的state
// getters用户获取其他的getters
// rootState拿到根的state
// rootGetters拿到根getters
doubleHomeCounter(state, getters, rootState, rootGetters) {
return state.homeCounter * 2
},
otherGetter(state) {
return 100
}
},
mutations: {
increment(state) {
state.homeCounter++
}
},
actions: {
// 一个参数,对齐进行解构
// commit: 提交
// dispatch: 分发
// state: 当前state
// rootState: 根state
// getters: 当前getters
// rootGetters: 根getters
incrementAction({commit, dispatch, state, rootState, getters, rootGetters}) {
// 这里提交commit,默认提交的是当前模块的commit
commit("increment")
// 如果我们想提交根模块的commit,需要第三个参数
// 参数一: 提交的方法名字
// 参数二: payload,也就是传递给increment方法的参数
// 参数三: {root: true}代表是根的commit
commit("increment", null, {root: true})
// 同理dispatch也是一样
// dispatch("incrementAction", null, {root: true})
}
}
}
export default homeModule
区别:store里面有state、getters、commit、dispatch,context不但有这些东西,它还会引用root的一些东西,比如rootState和rootGetters,这也是它们的区别。
module的辅助函数
前面我们使用辅助函数是这样使用的:
computed: {
...mapState(["homeCounter"]),
...mapGetters(["doubleHomeCounter"])
},
methods: {
...mapMutations(["increment"]),
...mapActions(["incrementAction"]),
},
这样写只是获取根里面的,如果不是根里面,就需要指定模块名了。
方式一:通过完整的模块空间名称来查找(用的少);
方式二:第一个参数传入模块空间名称,后面写上要使用的属性(用的多);
方式三:通过 createNamespacedHelpers 生成一个模块的辅助函数(更推荐);
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
// 1.写法一:
computed: {
homeCounter: state => state.home.homeCounter
}),
...mapGetters({
doubleHomeCounter: "home/doubleHomeCounter"
})
// 2.写法二:
...mapState("home", ["homeCounter"]),
...mapGetters("home", ["doubleHomeCounter"])
},
methods: {
// 1.写法一:
...mapMutations({
increment: "home/increment"
}),
...mapActions({
incrementAction: "home/incrementAction"
}),
// 2.写法二
...mapMutations("home", ["increment"]),
...mapActions("home", ["incrementAction"]),
},
}
</script>
第三种方式:我们可以使用vuex里的createNamespacedHelpers函数,然后解构函数的返回值。
<script>
// 导入函数
import { createNamespacedHelpers } from "vuex";
// 解构返回值
const { mapState, mapGetters, mapMutations, mapActions } = createNamespacedHelpers("home")
export default {
computed: {
// 3.写法三:
...mapState(["homeCounter"]),
...mapGetters(["doubleHomeCounter"])
},
methods: {
// 3.写法三:
...mapMutations(["increment"]),
...mapActions(["incrementAction"]),
},
}
</script>
通过createNamespacedHelpers函数,我们的写法就和以前在根里面写的一样了,更推荐这种方式。
在setup中使用
对于state和getters,如果在setup中使用我们可以用以前封装的useState.js和useGetters.js,但是以前我们封装useState.js和useGetters.js的时候没有考虑模块,所以现在我们要重新封装。
useState.js文件代码:
import { mapState, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'
export function useState(moduleName, mapper) {
// 默认是根的mapState
let mapperFn = mapState
// 传模块名和数组
if (typeof moduleName === 'string' && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapState
} else {
// 只传一个参数,那传的就是mapper
mapper = moduleName
}
return useMapper(mapper, mapperFn)
}
useGetters.js文件代码:
import { mapGetters, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'
export function useGetters(moduleName, mapper) {
let mapperFn = mapGetters
if (typeof moduleName === 'string' && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapGetters
} else {
mapper = moduleName
}
return useMapper(mapper, mapperFn)
}
组件中使用如下:
import { useState, useGetters } from '../hooks/index'
// 解构返回值
const { mapMutations, mapActions } = createNamespacedHelpers("home")
setup() {
const rootState = useState(["rootCounter"])
const rootGetters = useGetters(["doubleRootCounter"])
// 指定模块
const getters = useGetters("home", ["doubleHomeCounter"])
// 对于mutations和actions是使用createNamespacedHelpers处理过的,所以没问题
const mutations = mapMutations(["increment"])
const actions = mapActions(["incrementAction"])
return {
...rootState,
...rootGetters
...getters,
...mutations,
...actions
}
}