1. Vuex 概述
1.1 组件之间共享数据的方式
父向子传值:v-bind 属性绑定
子向父传值:v-on 事件绑定
兄弟组件之间共享数据:EventBus
$on
接收数据的那个组件$emit
发送数据的那个组件
1.2 Vuex是什么
Vuex
是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享。
2. Vuex 的基本使用
- 安装 vuex 依赖包
npm install vuex --save
- 导入 vuex 包
import Vuex from 'vuex'
Vue.use(Vuex)
- 创建 store 对象
const store = new Vuex.Store({
//state 中存放的就是全局共享的数据
state: {count:0}
- 将 store 对象挂载到 vue 实例中
new Vue({
el:'#app',
render:h => h(app),
router,
//将创建的共享数据对象,挂载到 Vue 实例中
//所有的组件,就可以直接从 store 中获取全局的数据了
store
})
3. Vuex 的核心概念
3.1 核心概念概述
Vuex 核心概念如下:
- State
- Mutation
- Action
- Getter
3.2 State
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储
// 创建 store 数据源,提供唯一公共数据源
const store = new Vuex.store({
state:{ count:0 }
})
组件访问State中数据的第一种方式:
this.$store.state.全局数据名称
组件访问State中数据的第二种方式:
//1.从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
//2.通过导入的 mapState 函数,将全局数据,映射为当前组件的计算属性
computed:{
...mapState({'count'})
}
3.3 Mutation
Mutation 用于变更 Store 中的数据
//定义 Mutation
const store = new Vuex.store({
state:{ count:0 },
mutations:{
add(state){
state.count++
}
}
})
触发 mutations 的第一种方式
//触发 mutation
methods:{
handle1(){
//触发 mutations 的第一种方式
this.$store.commit('add')
}
}
可以在触发 mutations 时传递参数:
//定义 Mutation
mutations:{
addN(state,step) {
state.count += step
}
}
//触发 mutation
methods:{
handle1(){
//触发 mutations 时携带参数
//commit 作用就时调用某个 mutation 函数
this.$store.commit('addN',3)
}
}
触发 mutations 的第二种方式
// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'
// 2. 将指定的mutations函数,映射为当前组件的methods函数
methods:{
...mapMutations(['add','addN'])
}
3.4 Action
在mutations中不能编写异步的代码,在vuex中我们可以使用Action来执行异步操作
//定义 Action
actions:{
addAsync(context){
setTimeout(() => {
context.commit('add')
},1000)
}
}
// 触发 Action
methods:{
handle(){
//第一种方式
//dispaych作用,专门调用action函数
this.$store.dispatch('addAsync')
}
}
触发 actions 异步任务时携带参数:
//定义 Action
actions:{
addAsync(context,step){
setTimeout(() => {
context.commit('addN',step)
},1000)
}
}
//触发 action
methods:{
handle(){
this.$store.dispatch('addNAsync',5)
}
}
this.$store.dispatch() 是触发 action 的第一种方法,触发 action 的第二种方法:
//1.从 vuex 中按需导入 mapActions 函数
import { mapAction } from 'vuex'
//2.将指定的 actions 函数,映射为当前组件的 methods 函数
methods:{
...mapActions(['addAsync','addNAction'])
}
3.5 Getter
Getter 用于对Store中的数据进行加工处理形成新的数据
- Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
- Store 中的数据发生变化,Getter的数据也会跟着变化
//定义Getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state => {
return '当前最新的数量是【'+state.count+'】'
}
}
})
使用 getters 的第一种方式
this.$store.getters.名称
使用 getters 的第二种方式
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}