Vuex 概述
1.1 组件之间数据共享的方式
- 父向子传值:v-bind 绑定
- 子向父传值: v-on 事件绑定
- 兄弟组件之间共享数据 : EventBus
- $on 接受数据的组件
- $emit 发送数据的组件
1.2 Vuex 是什么?
Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享
1.3 使用 Vuex 统一管理状态的好处
- 能够在Vuex中集中管理共享的数据,已与开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在Vuex 中的数据都是响应式的,能够实时保持数据与页面的同步
1.4 什么样的数据适合存储到 Vuex中?
一般情况下,只有组件之间共享的数据,才有必要存储到Vuex中,对于组件中的私有数据,依然存储在组件自身的data中
Vuex 核心概念
2.1 State
State 提供位移的公共数据源,所有共享的数据都要统一放到Store 的State中进行存储
//创建State数据源,提供唯一公共数据
const store = new Vuex.Store({
State :{count:0}})
组件中访问State中数据的第一种方式:
this.$store.state.全局数据名称
组件中访问State中数据的第二种方式:
// 1. 从Vuex 中 按需导入 mapState 函数
import {mapState} from 'Vuex'
// 2. 将全局数据,映射为当前组件的计算属性
computed:{
...mapState(['count'])
2.2 Mutation
Mutation 用于变更Store 中的数据
- 只能通过mutation 变更Store数据,不可以直接操作Store中的数据
- 虽然繁琐但是可以集中监控所有数据的变化
//定义 mutation
const store = new Vuex.Store({
state:{
count:0},
mutations:{
add(state,step){
state.count+=step}}
})
//触发mutation 的第一种方式
methods:{
handle(){
this.$store.commit('add',5)}
}
//触发mutation 的第二种方式
//1. 从Vuex 中导入 mapMutations 函数
import {mapMutation} from 'vuex'
//2 将指定的mutations 函数映射为当前组件中的 methods 函数
methods:{
...mapMutation(['add','addN'])}
2.3 Action
Action 用于处理异步任务 如果通过异步操作变更数据,必须通过Action,而不能使用mutation 但在Action 中还是要通过触发Mutation的方式间接变更数据
//定义Action
const
store = new Vuex.Store({
mutations:{
add(state,step){
state.count+=step}}
actions:{
addSync(context,step){
setTimeout(()=>{
context.commit('add',step),1000})}}
})
//2. 触发Action
methods:{
handle(){
//触发 actions 的第一种方式
this.$store.dispath('addSync',5)
}}
//触发 actions 的第二种方式
import {mapActions} from 'Vuex'
methods:{
...mapAction(['addSync'])
}
2.4 Getter
Getter 用于对Store 中的数据进行加工处理形成新的数据
- Getter 可以对 Store中已有的数据进行加工处理形成新的数据,类似Vue的计算属性
- Store中的数据发生变化 Getter 的数据也会跟着变化
// 1. 定义 Getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state =>{
return '当前数据'+state.count
}}
})
//2. 使用 getter 的第一种方式
this.$store.getters.名词
// 使用getter 的第二种方式
import {mapGetters} from 'Vuex'
computed:{
...mapGetters(['showNum'])}