# Vuex

Vuex 简介

什么是 vuex

  • 概念:专门在 Vue 中实现集中式状态(数据)管理的一个 Vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

  • 什么时候使用 vuex:

    • 01 多个组件依赖于同一状态
    • 02 来自不同组件的行为需要变更同—状态

1673879146237

1673879166417

纯 vue 实现计数器案例

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div>
<Count></Count>
</div>
</template>

<script>
import Count from './components/Count'
export default {
name: 'App',
components: { Count },
}
</script>

<style scoped></style>

Count.vue:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<template>
<div>
<h1>当前求和为:{{ sum }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>

<script>
export default {
data() {
return {
n: 1, //用户选择的数字
sum: 0, //当前的和
}
},
methods: {
increment() {
this.sum += this.n
},
decrement() {
this.sum -= this.n
},
incrementOdd() {
if (this.sum % 2) {
this.sum += this.n
}
},
incrementWait() {
setTimeout(() => {
this.sum += this.n
}, 500)
},
},
}
</script>

<style scoped>
button {
margin-right: 5px;
}
</style>

Vuex 工作原理图

1651640511206

1651640854369

vuex 的使用

  • 01 安装 vuex
1
2
3
npm install vuex@3
# 在 vue2 中不能使用最新版的 vuex4,否则会报错....只能使用 vuex3
# 在 vuex3 中只能使用 vuex4
  • 02 引入 vuex 并使用 vuex 插件,并配置数据仓库

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//该文件用来创建Vuex中最为核心的store

//导入vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//应用vuex
Vue.use(Vuex)

//准备state
const state = {}
//准备mutations
const mutations = {}
//准备actions
const actions = {}

//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
  • 03 在 main.js 中导入并注册 store 数据仓库即可
1
2
3
4
5
6
7
8
9
10
import Vue from 'vue'
import App from './App.vue'

import store from './store/index.js' //导入store

Vue.config.productionTip = false
new Vue({
render: (h) => h(App),
store,
}).$mount('#app')

vuex 实现计数器案例

  • 01 在按钮的点击事件回调中派发 actions 或提交 mutations
    • 派发 actions 时,参数一要与 actions 中的方法名一致
    • 直接提交 mutations 时,参数一要与 mutations 中的方法名一致,通常为全部大写,
    • 通过 mutations 修改 state,若在 actions 中操作 state,则开发者工具就派不上用场了
  • 04 在组件模板中可以通过 $store.state.sum ,JS 中通过 this.$store.state.sum 获取到数据仓库 state 中的数据

Count.vue:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<template>
<div>
<h1>当前求和为:{{ $store.state.sum }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>

<script>
export default {
data() {
return {
n: 1, //用户选择的数字
}
},
methods: {
increment() {
//没有其他业务逻辑,可以派发actions,再提交mutations
this.$store.dispatch('jia', this.n)
},
decrement() {
//没有其他业务逻辑,也可以直接提交mutations
this.$store.commit('JIAN', this.n)
},
incrementOdd() {
//有其他业务逻辑,派发actions,在actions处理业务逻辑
this.$store.dispatch('jiaOdd', this.n)
},
incrementWait() {
//有其他业务逻辑,派发actions,在actions处理业务逻辑
this.$store.dispatch('jiaWait', this.n)
},
},
}
</script>

<style scoped>
button {
margin-right: 5px;
}
</style>
  • 02 在数据仓库的 actions 中,进行其他业务处理,并提交 mutations

    • 提交 mutations 时,参数一通常为该方法名的全部大写,与 mutations 中的方法名一致
  • 03 在 mutations 中操作 state 中的数据

./src/store/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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//该文件用来创建Vuex中最为核心的store

//导入vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//应用vuex
Vue.use(Vuex)

//准备state
const state = { sum: 0 }

//准备mutations
const mutations = {
//形参一:state对象 形参二:传递过来的数据
JIA(state, value) {
state.sum += value
},
JIAN(state, value) {
state.sum -= value
},
JIAODD(state, value) {
state.sum += value
},
JIAWAIT(state, value) {
state.sum += value
},
}

//准备actions
const actions = {
//形参一:上下文 形参二:传递过来的参数
jia(context, value) {
//提交mutations
context.commit('JIA', value)
},
// jian(context, value) {
// context.commit("JIAN", value);
// },
jiaOdd(context, value) {
//进行判断
if (context.state.sum % 2) {
context.commit('JIAODD', value)
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit('JIAWAIT', value)
}, 500)
},
}

//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})

getters 对 state 的操作

  • 01 在以上案例的基础上,添加 getters 配置项,对 state 进行加工/简化操作

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//准备getters  对state数据的加工简化操作,相当于计算属性
const getters = {
//state:即存储数据的state
bigSum(state) {
return state.sum * 10
},
}

//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
getters,
})
  • 02 在组件模板 [或 JS ] 中通过 [this.]$store.getters.bigSum 获取到经过 getters 加工过的数据

Count.vue:

1
<h1>当前求和放大10倍:{{ $store.getters.bigSum }}</h1>

mapState

  • 01 在数据仓库中准备数据

./src/store/index.js:

1
2
3
4
5
//准备state
const state = {
school: '尚硅谷',
subject: '前端',
}
  • 02 在组件中获取数据,从 vuex 中导入 mapState
  • 03 在组件的计算属性中,进行简化操作
  • 04 在组件模块中使用数据

Count.vue:

1
import { mapState } from 'vuex'
1
2
3
4
5
6
7
8
9
computed:{
//借助 mapState 生成计算属性,从 state 中读取数据。(对象写法)
//对象中的属性:为当前组件要使用的变量名,起名任意 参数二:state中的变量名
//...mapState({school:"school",xueke:"subject"})

//借助mapState生成计算属性,从state中读取数据。(数组写法)
//数组中的元素有两个作用:1.使用数据时的变量名, 2.state中的变量名
...mapState(["school","subject"])
},
1
2
<!-- <h1>学校:{{ school }},,,学科:{{ xueke }}</h1> -->
<h1>学校:{{ school }},,,学科:{{ subject }}</h1>

mapGetters

  • 01 在数据仓库的 getters 中对数据进行加工简化操作

./src/store/index.js:

1
2
3
4
5
6
//准备getters  对state数据的加工简化操作,相当于计算属性
const getters = {
bigSum(state) {
return state.sum * 10
},
}
  • 02 在组件中获取数据,,从 vuex 中导入 mapGetters

  • 03 在组件的计算属性中,进行简化操作

  • 04 在组件模块中使用数据

Count.vue:

1
import { mapState, mapGetters } from 'vuex'
1
2
3
4
5
6
7
computed:{
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
//...mapGetters({bigSum:"bigSum"})

//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
...mapGetters(["bigSum"])
},
1
<h1>当前求和放大10倍:{{ bigSum }}</h1>

mapMutation

  • 01 在数据仓库的 mutations 中:

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
//准备mutations
const mutations = {
//形参一:state对象 形参二:传递过来的数据
JIA(state, value) {
state.sum += value
},
JIAN(state, value) {
state.sum -= value
},
}
  • 02 在组件中获取数据,,从 vuex 中导入 mapMutations

  • 03 在组件的 methods 方法中,进行简化操作

  • 04 在组件模块中使用方法

Count.vue:

1
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
methods: {
// increment() {
// this.$store.commit("jIA", this.n);
// },
// decrement() {
// this.$store.commit("JIAN", this.n);
// },

//(对象写法) 方法调用时,需要加括号传递参数,否则参数为事件对象
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
//对象中的属性:使用时调用的方法名 属性值:数据仓库中的mutations方法名
...mapMutations({ increment: "JIA", decrement: "JIAN" }),

//数组写法: 参数的两个作用:使用时调用的方法名 和 数据仓库中的mutations方法名
//...mapMutations(["JIA","JIAN"]),
}
1
<button @click="increment(n)">+</button> <button @click="decrement(n)">-</button>

mapActions

  • 01 在数据仓库的 actions 中:

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//准备actions
const actions = {
//形参一:上下文 形参二:传递过来的参数
jiaOdd(context, value) {
//进行判断
if (context.state.sum % 2) {
context.commit('JIAODD', value)
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit('JIAWAIT', value)
}, 500)
},
}
  • 02 在组件中获取数据,,从 vuex 中导入 mapActions

  • 03 在组件的 methods 方法中,进行简化操作

  • 04 在组件模块中使用方法

Count.vue:

1
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
methods: {
/*=================================================*/
// incrementOdd() {
// this.$store.dispatch("jiaOdd", this.n);
// },
// incrementWait() {
// this.$store.dispatch("jiaWait", this.n);
// },

//借助 mapActions生成对应的方法,方法中会调用dispatch去联系actions
//对象写法,方法调用时,需要加括号传递参数,否则参数为事件对象
...mapActions({incrementOdd:"jiaOdd",incrementWait:"jiaWait"}),
//数组写法,方法调用时,需要加括号传递参数,否则参数为事件对象
//...mapActions(["jiaOdd","jiaWait"])
},
1
<button @click="incrementOdd(n)">当前求和为奇数再加</button> <button @click="incrementWait(n)">等一等再加</button>

多组件共享数据

  • 01 在数据仓库中准备数据

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//准备state
const state = {
sum: 0,
school: '尚硅谷',
subject: '前端',
personList: [{ id: '001', name: '张三' }],
}

//准备mutations
const mutations = {
//...

ADD_PERSON(state, value) {
state.personList.unshift(value)
},
}
  • 02 在 Person.vue 组件中创造一个数据,并添加到数据仓库中
  • 03 在 Person.vue 组件中获取数据仓库中的 sum 数据,并展示在页面中
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
33
34
35
36
37
<template>
<div>
<hr />
<h1>人员列表</h1>
<input type="text" placeholder="请输入姓名" v-model="name" />
<button @click="add">添加</button>
<h1>求和为:{{ sum }}</h1>
<ul>
<li v-for="p in presonList" :key="p.id">{{ p.name }}</li>
</ul>
</div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
components: {},
data() {
return { name: '' }
},
methods: {
add() {
const personObj = { id: nanoid(), name: this.name }
this.$store.commit('ADD_PERSON', personObj)
this.name = ''
},
},
computed: {
presonList() {
return this.$store.state.personList
},
sum() {
return this.$store.state.sum
},
},
}
</script>
  • 04 在 Count.vue 组件中获取到数据仓库中的 personList 数据,并展示在页面中
1
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
1
2
3
4
computed: {
...mapState(["school", "subject","personList"]),
...mapGetters(["bigSum"]),
},
1
<h1>下方列表的总人数是:{{personList.length}}</h1>

vuex 模块化与命名空间 1

  • 01 在数据仓库中,将各项模块化,并开启命名空间

./src/store/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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//该文件用来创建Vuex中最为核心的store

//导入vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//应用vuex
Vue.use(Vuex)

//计算相关
const countOptions = {
namespaced: true, //开启命名空间
state: { sum: 0, school: '尚硅谷', subject: '前端' },
mutations: {
JIA(state, value) {
state.sum += value
},
JIAN(state, value) {
state.sum -= value
},
JIAODD(state, value) {
state.sum += value
},
JIAWAIT(state, value) {
state.sum += value
},
},
actions: {
jiaOdd(context, value) {
if (context.state.sum % 2) {
context.commit('JIAODD', value)
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit('JIAWAIT', value)
}, 500)
},
},
getters: {
bigSum(state) {
return state.sum * 10
},
},
}
//人员相关
const personOptions = {
namespaced: true, //开启命名空间
state: { personList: [{ id: '001', name: '张三' }] },
mutations: {
ADD_PERSON(state, value) {
state.personList.unshift(value)
},
},
actions: {},
getters: {},
}

//创建并暴露store
export default new Vuex.Store({
modules: {
countAbout: countOptions,
personAbout: personOptions,
},
})
  • 02 在组件中获取数据仓库中的数据

Count.vue:

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
33
34
35
36
37
38
39
40
41
<template>
<div>
<h1>当前求和为:{{ sum }}</h1>
<h1>当前求和放大10倍:{{ bigSum }}</h1>
<h1>下方列表的总人数是:{{ personList.length }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
<hr />
<h1>学校:{{ school }},,,学科:{{ subject }}</h1>
</div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
data() {
return {
n: 1,
}
},
computed: {
...mapState('countAbout', ['school', 'subject', 'sum']),
...mapState('personAbout', ['personList']),
...mapGetters('countAbout', ['bigSum']),
},
methods: {
...mapMutations('countAbout', { increment: 'JIA', decrement: 'JIAN' }),
...mapActions('countAbout', {
incrementOdd: 'jiaOdd',
incrementWait: 'jiaWait',
}),
},
}
</script>

Person.vue

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
33
34
35
36
37
38
39
<template>
<div>
<hr />
<h1>人员列表</h1>
<input type="text" placeholder="请输入姓名" v-model="name" />
<button @click="add">添加</button>
<h1>求和为:{{ sum }}</h1>
<ul>
<li v-for="p in presonList" :key="p.id">{{ p.name }}</li>
</ul>
</div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
components: {},
data() {
return { name: '' }
},
methods: {
add() {
const personObj = { id: nanoid(), name: this.name }
this.$store.commit('personAbout/ADD_PERSON', personObj)
this.name = ''
},
},
computed: {
presonList() {
return this.$store.state.personAbout.personList
},
sum() {
return this.$store.state.countAbout.sum
},
},
}
</script>

<style scoped lang="less"></style>

vuex 模块化与命名空间 2

  • 01 将数据仓库划分多个小仓库

./src/store/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//该文件用来创建Vuex中最为核心的store

//导入vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//引入小仓库
import countOptions from './countOptions.js'
import personOptions from './personOptions.js'
//应用vuex
Vue.use(Vuex)

//创建并暴露store
export default new Vuex.Store({
modules: {
countAbout: countOptions,
personAbout: personOptions,
},
})

./src/store/countOptions.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
26
import axios from 'axios'
import { nanoid } from 'nanoid'

export default {
namespaced: true, //开启命名空间
state: { personList: [{ id: '001', name: '张三' }] },
mutations: {
ADD_PERSON(state, value) {
state.personList.unshift(value)
},
},
actions: {
//发起请求,获取数据
addPersonServer(context) {
axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
(response) => {
context.commit('ADD_PERSON', { id: nanoid(), name: response.data })
},
(error) => {
alert(error.message)
}
)
},
},
getters: {},
}

./src/store/personOptions.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
26
27
28
29
30
31
32
33
34
35
export default {
namespaced: true, //开启命名空间
state: { sum: 0, school: '尚硅谷', subject: '前端' },
mutations: {
JIA(state, value) {
state.sum += value
},
JIAN(state, value) {
state.sum -= value
},
JIAODD(state, value) {
state.sum += value
},
JIAWAIT(state, value) {
state.sum += value
},
},
actions: {
jiaOdd(context, value) {
if (context.state.sum % 2) {
context.commit('JIAODD', value)
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit('JIAWAIT', value)
}, 500)
},
},
getters: {
bigSum(state) {
return state.sum * 10
},
},
}
  • 02 在组件中获取数据仓库中的数据

Person.vue:

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
33
34
35
36
37
38
39
40
41
42
<template>
<div>
<hr />
<h1>人员列表</h1>
<input type="text" placeholder="请输入姓名" v-model="name" />
<button @click="add">添加</button>
<button @click="addPersonServer">发起请求</button>
<h1>求和为:{{ sum }}</h1>
<ul>
<li v-for="p in presonList" :key="p.id">{{ p.name }}</li>
</ul>
</div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
components: {},
data() {
return { name: '' }
},
methods: {
add() {
const personObj = { id: nanoid(), name: this.name }
this.$store.commit('personAbout/ADD_PERSON', personObj)
this.name = ''
},
addPersonServer() {
//通知数据仓库发起网络请求获取数据
this.$store.dispatch('personAbout/addPersonServer')
},
},
computed: {
presonList() {
return this.$store.state.personAbout.personList
},
sum() {
return this.$store.state.countAbout.sum
},
},
}
</script>

Count.vue:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<template>
<div>
<h1>当前求和为:{{ sum }}</h1>
<h1>当前求和放大10倍:{{ bigSum }}</h1>
<h1>下方列表的总人数是:{{ personList.length }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
<hr />
<h1>学校:{{ school }},,,学科:{{ subject }}</h1>
</div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
data() {
return {
n: 1, //用户选择的数字
}
},
computed: {
...mapState('countAbout', ['school', 'subject', 'sum']),
...mapState('personAbout', ['personList']),
...mapGetters('countAbout', ['bigSum']),
},
methods: {
...mapMutations('countAbout', { increment: 'JIA', decrement: 'JIAN' }),
/*=================================================*/
...mapActions('countAbout', {
incrementOdd: 'jiaOdd',
incrementWait: 'jiaWait',
}),
},
}
</script>

<style scoped>
button {
margin-right: 5px;
}
</style>