vuex 是一个插件,可以帮我们管理 vue 通用的数据 (多组件共享的数据)
2. 场景:
① 某个状态 在 很多个组件 来使用 (个人信息)
② 多个组件 共同维护 一份数据 (购物车)
3. 优势:
① 共同维护一份数据,数据集中化管理
② 响应式变化
③ 操作简洁 (vuex提供了一些辅助函数)
构建 vuex [多组件数据共享] 环境
效果是三个组件, 共享一份数据:
l 任意一个组件都可以修改数据
l 三个组件的数据是同步的
state 状态
1. 提供数据:
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 中的 State 中存储。
在 state 对象中可以添加我们要共享的数据。
/ 创建仓库
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data
// 区别:
// 1. data 是组件自己的数据
// 2. state 是所有组件共享的数据
state: {
count: 101
}
})
2. 使用数据:
① 通过 store 直接访问
(1) this.$store
(2) import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx
② 通过辅助函数
mapState是辅助函数,帮助我们把 store中的数据 自动 映射到 组件的计算属性中
核心概念 - mutations
1. 定义 mutations 对象,对象中存放修改 state 的方法
const store = new Vuex.Store({
state: {
count: 0
},
// 定义mutations
mutations: {
// 第一个参数是当前store的state属性
addCount (state) {
state.count += 1
}
}
})
2. 组件中提交调用 mutations
this.$store.commit('addCount')
1. 提供 mutation 函数 (带参数 - 提交载荷 payload )
mutations: {
...
addCount (state, n) {
state.count += n
}
},
2. 页面中提交调用 mutation
this.$store.commit('addCount', {
count: 10,
...
})
Tips: 提交参数只能一个,如果有多个参数,包装成一个对象传递
this.$store.commit('addCount', 10)
辅助函数 - mapMutations
mutations: {
subCount (state, n) {
state.count -= n
},
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['subCount'])
}
this.subCount(10) 调用
methods: {
subCount (n) {
this.$store.commit('subCount', n)
},
}
mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中
核心概念 - getters
1. 定义 getters
getters:{
// (1) getters函数的第一个参数是 state
// (2) getters函数必须要有返回值
filterList (state) {
return state.list.filter(item => item > 5)
}
}
1
2. 访问getters
① 通过 store 访问 getters
{{ $store.getters.filterList }}
② 通过辅助函数 mapGetters 映射
computed: {
...mapGetters(['filterList'])
},
{{ filterList }}
核心概念 - 模块 module (进阶语法)
使用模块中 getters 中的数据:
① 直接通过模块名访问 $store.getters['模块名/xxx ']
② 通过 mapGetters 映射
默认根级别的映射 mapGetters([ 'xxx' ])
子模块的映射 mapGetters('模块名', ['xxx']) - 需要开启命名空间
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
综合案例 - 购物车
调整初始化目录
1. 删除 多余的文件
2. 修改 路由配置 和 App.vue
3. 新增 两个目录 api / utils
① api 接口模块:发送ajax请求的接口模块
② utils 工具模块:自己封装的一些工具方法模块
vant 全部导入 和 按需导入
项目中的 vw 适配