Vuex使用

Vuex使用

什么时候需要使用vuex? 1.当项目使用了vue-router,并且多个页面之间需要共享数据的时候。 2.共享数据难以统一管理的时候。

1.安装vuex

1
npm install --save vuex

2.在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
// 1.引入 vue
import Vue from 'vue';
// 2.引入vuex
import Vuex from "vuex"
// 3.调用 vuex
Vue.use(Vuex);
// 4.定义仓库的 state、getters、mutations、actions、modules
const state = {
name:"泰勒斯威夫特"
}
const getters = {

}
// 5.实例化仓库对象
const store = new Vuex.Store({
// 选项配置:state、getters、mutations、actions、modules
state:state,
getters
});
// 6.暴露仓库实例对象
export default store;

3.在Vue 实例中配置

在 main.js 中,即 new Vue 的时候配置 store 这个选项,选项的值就是 store 的实例对象

1
2
3
4
5
new Vue({
store:store,
router,
render: h => h(App),
}).$mount('#app')

4.在组件中使用仓库的数据

####4.1使用 mapState() 这个辅助函数

1
2
3
4
5
<template>
<div>
<h1>仓库中 name 为:{{ name }}</h1>
</div>
</template>
1
2
3
4
5
import { mapState } from 'vuex'
export default {
// 定义计算属性
computed: mapState(["name"])
}

4.2使用 mapState 辅助函数时,如果组件需要定义自己的计算属性,可以使用...运算符

1
2
3
4
5
6
7
8
9
export default {
// 定义计算属性
computed: {
...mapState(["name"]),
list01: function(){
return ["sd","df"]
}
}
}

5.修改仓库中的数据

1.首先在仓库的 mutations 部分定义一个修改 state 数据的方法

1
2
3
4
5
6
const mutations = {
// 除了接收到state,还能接受一个 payload(参数)
setName(state,payload){
state.name = payload.newName
}
}

2.组件中在methods中使用 mapMutations 这个辅助函数

1
2
3
methods:{
...mapMutations(["setName"])
}

上述写法展开为:

1
2
3
4
5
6
methods:{
setName(payload){
//commit 方法用来提交 mutation 的
this.$store.commit('setName',payload);
}
}
### 6.获取仓库中 getters 的数据 使用 mapGetters 这个辅助函数即可。

7.异步地修改仓库中的 state 数据,如 ajax、setTimeout

7.1在组件中,异步完成之后,再 commit mutations

7.2使用actions

8.modules选项

将仓库中 state 的数据,按照某种格式来做拆分,拆分成一个个小的module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
#### 8.1子模块 子模块写法:暴露一个对象(包含state、mutations、getters、actions、modules等),可以继续嵌套子模块。子模块建议设置命名空间,否则子模块除 state 外其他全部会挂载到全局命名空间下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 子模块 cart.js
export default{
namespaced: true, //注意设置命名空间
state:{
carts:[]
},
getters:{},
mutations:{
add(){ // 定义
//...
}
},
actions:{}
}

8.2在主模块配置子模块

1
2
3
4
5
6
7
8
9
10
11
import Vue from "vue"
import Vuex from "vuex"
// 引入拆分出去的仓库小模块
import cart from "./modules/cart"
Vue.use(Vuex)
// 实例化仓库的实例对象
export default new Vuex.Store({
modules:{
cart
}
})

8.3在组件中调用

1
2
3
4
5
6
7
8
9
10
11
import { mapMutations } from 'vuex'
export default {
computed:{},
methods:{
//...mapMutations("cart",["add"]) // 调用,cart为命名空间
// 展开写法如下
fn1(){
this.$store.commit("cart/adds") //注意这种写法,但推荐上述写法
}
}
}