Vuex
bridge 2022/9/25
# 概述
全局状态管理
# 优点
集中管理 方便传值 数据响应式
# 核心概念
# State
提供唯一的公共数据源,所有共享数据都要放到state中
- 访问
- 直接通过
this.$store.state.全局数据名称
读取 - 借助 mapState 函数,将全局数据映射为当前组件的 computed 计算属性
import { mapState } from 'Vuex'
computed: {
...mapState(['全局数据名称'])
}
# Mutation
用于变更 Store 中的数据,只能定义同步方法,只能通过 mutation 提供的方法变更 Store 的数据,方便管理
- 定义
const store = new Vuex.Store({
state: {
},
mutations: {
add(state){//定义操作}
}
})
- 组件内使用
- 使用 commit 调用
this.$store.commit('add')
- 借助 mapMutations 函数将mutations 定义的方法映射为 method
import {mapMutations} from 'Vuex'
methods: {
...mapMutations(['函数名'])
}
# Action
用于定义异步方法,但涉及到变更store数据时,仍必须通过调用 mutation 的方法来实现
定义
调用
- 使用 dispatch 调用
this.$store.dispatch('函数名')
- 借助 mapActions 函数将mutations 定义的方法映射为 method
# Getter
对 Store 中的数据进行加工处理,不会修改 store 中的数据,类似于 computed 计算属性。当 store 中数据改变,getter也会对应改变
- 定义
const store = new Vuex.Store({
state:{
},
getters:{
}
})
- 调用
- 直接调用
this.$store.getter.属性名
- 借助 mapGetters 函数将getters 定义的属性映射为 computed
# Module
模块化 Vuex,让每个模块能有自己的 state、mutation、action、getter