如何提供 或 访问 vuex 的数据、mutations 修改 vuex 的数据
目标:明确如何给仓库提供数据,如何使用仓库的数据
一、提供数据:
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 中的 State 中存储。在 state 对象中可以添加我们要共享的数据。
// state : 状态,即数据,类似于 vue 组件中的 data(区别:data 是组件自己的数据,state 是所有组件共享的数据)
const store = new Vuex.Store({
state : {
count : 101
}
})
二、使用数据:
1. 通过 store 直接访问:
// 获取 store:this.$store 或 import 导入 store
模板中:{{ $store.state.count }}
组件逻辑中:this.$store.state.count
JS 模块中:store.state.count
2. 通过辅助函数(简化):
mapState 是辅助函数,帮助我们把 store 中的数据 自动 映射到 组件的计算属性中
1. 导入 mapState:import { mapState } from 'vuex'
2. 以数组的形式引入 state
3. 展开运算符映射
------------------------------------------------------------------------------------------------------------------------------------
mutations:修改仓库的数据
mutations 必须是同步的(便于监测数据变化,记录调试)
mutations 是 vuex 当中的一个对象,可以定义在 Store 的配置项当中,mutations 里面可以存放一系列方法,而这些方法全都是用来修改 state 数据的。
知识点:vuex 同样遵循单项数据流,组件中不能直接修改仓库的数据。应该通过 mutations 进行修改数据
使用 mutations:
一、不传参
1. 定义 mutations 对象,对象中存放修改 state 中数据的方法(所有 mutations 里定义的函数,第一个参数都是 state)
const store = new Vuex.Store({
state : {
count : 101
} ,
mutations: {
addCount (state) {
state.count += 1
}
}
})
2. 组件中提交调用 mutations:
this.$store.commit (' addCount ' ) // addCount 是第 1 步中方法的名字
二、传参
1. mutations 对象里提供函数(只能传一个参数。如果需要传递多个数据,就要把数据打包成 数组或对象)
mutations: {
addCount (state , num ) {
state.count += num
}
}
2. 组件中调用 mutations 时传参:
this.$store.commit ( ' xxx ' , 参数 ) // xxx:mutations 中方法的名字