1、定义
Vuex官网
是:状态管理模式
什么时候用:多个界面间的共享:比如登录状态、用户的头像
1.1安装
1、在创建项目的时候会选择安装 Vuex 直接回安装好;
1、安装:npm install vuex --save
2、引入:一般会在src下建一个store文件夹
3、vue3 创建 store
##1.2 Vuex状态管理图例
2.实现 点击加减修改store 中state里面的counter值
#3.五个核心概念
- State
- Getters
- Mutations
- Actions
- Modules
3.1 State 单一状态树
3.2 Getters
可以认为是 store 的计算属性
Getter
1.接受 state 作为其第一个参数
2.也可以接受其他 getter 作为第二个参数:
3.就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来, 且只有当它的依赖值发生了改变才会被重新计算。 \color{red}{且只有当它的依赖值发生了改变才会被重新计算。} 且只有当它的依赖值发生了改变才会被重新计算。
###3.2.1 states作为参数
//store index.js 中
//state这个参数就是前面state单一状态树
getters: {
more20stu(state) {
return state.students.filter(n => n.age > 20)
},
}
//index.vue 中 引用getters里面的
<h2>getters:{{ $store.getters.more20stu }}</h2>
3.2.2 getter 作为参数
getters: {
more20stu(state) {
return state.students.filter(n => n.age > 20)
},
//这里的getters用了上面的方法
more20stuLenght(state,getters) {
return getters.more20stu.length
}
}
3.2.3 自己传入一个参数
//index.vue 中 8是自己传入的一个参数
<h2>自己传一个参数:{{$store.getters.moreagelength(8)}}</h2>
// 这里的function(age)中的age就是传递过来的参数 8
moreagelength(state) {
// return function (age) {
// return state.students.filter(n => n.age > age).length
// }
return (age) => {
return state.students.filter(n => n.age > age).length
}
}
比如年龄比较的时候 比较的年龄是自己传入的 不是在store中固定写死的
3.3 Mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
3.3.1
- 会接受 state 作为第一个参数
- 提交载荷(Payload) 可以自定义参数
在大多数情况下,载荷应该是一个对象
对象风格的提交方式:
Mutation 需遵守 Vue 的响应规则
- 最好提前在你的 store 中初始化好所有所需属性。
- 当需要在对象上添加新属性时,你应该如下 用响应式的方法 \color{red}{用响应式的方法} 用响应式的方法修改数据
3.3.2 使用常量替代 Mutation 事件类型
3.3.3 Mutation 必须是同步函数
3.4 Actions
Action 类似于 mutation,不同在于
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
3.4.1
3.4.2 传递参数
- 简单的传递参数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QjO6qEyo-1659142446604)(https://upload-images.jianshu.io/upload_images/25486178-8eae1325a3f796ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
- 方法 提示 完成
- 传递参数 并且异步操作完成时 给到提示
- 用Promise 完成异步操作和提示
3.5 Modules
应用变得非常复杂时,store 对象就有可能变得相当臃肿。Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter甚至是嵌套子模块
//里面用的方式 是和前面的一模一样的
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 的状态
//rootState这个参数是拿到根节点中state中的内容的
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}