Day01_vuex — 总结
vuex什么时候出场
跨组件通信(非父子关系)
父子关系:父传子(props,子传父($emit)
vuex使用步骤
-
下载 vuex
yarn add vuex -S -
导包
import Vuex from 'vuex' -
注册
给组件挂载
$store对象Vue.use(Vuex) -
创建
store实例const store = new Vuex.Store({ //... }) -
注入到 new Vue()中
给
$store赋值new Vue({ store, // ... })
vuex核心概念
五个核心概念
1、state
作用:存放共享的数据源
定义:
const store = new Vuex.Store({
state: {
变量名: 初始值,
// ...
}
})
使用:两种方式
-
直接
this.$store.state.变量名 -
映射:把vuex的东西给到具体的某个组件
// 1. 导入辅助函数 import { mapState } from 'vuex' // 2. 映射到计算属性 computed: { ...mapState(['要映射的变量名1', '要映射的变量名2',...]) }
mutations
作用:唯一、同步 修改 state,本质是一个个的函数
定义:
const store = new Vuex.Store({
mutations: {
函数名(state, 可选值) {
//
}
}
})
使用:两种方式
-
直接
this.$store.commit('mutation函数名', 值) -
映射
// 1. 导入辅助函数 mapMutations import { mapMutations } from 'vuex' // 2. 映射到methods中 methods: { ...mapMutations(['mutation函数名']) }
actions
作用:
本质也是一个个的函数
异步更新state,但是actions不能直接修改state,它里面放的只是异步操作,
最终必须通过commit到指定的mutation函数方可state的更新
定义:
const store = new Vuex.Store({
actions: {
函数名(store, 可选值) {
// 这里书写异步代码
}
}
})
使用:两种方式
-
直接
this.$store.dispatch('要调用的action函数名', 值) -
映射
// 1. 导入辅助函数 mapActions import { mapActions } from 'vuex' // 2. 映射到组件的methods中 methods: { ...mapActions(['要映射的action函数名']) }
getters
作用:vuex的计算属性,全局计算属性,类似组件的computed
场景:当数据变量依赖state中变量计算而得到,需要getters登场了
定义:
const store = new Vuex.Store({
getters: {
计算属性名(state) {
//...
return 新值
}
}
})
使用:两种方式
-
直接
this.$store.getters.计算属性名 -
映射
// 1. 导入辅助函数 mapGetters import { mapGetters } from 'vuex' // 2. 映射到组件的computed中 computed: { ...mapGetters(['要映射的计算属性']) }
modules
作用:分模块用的
提示
-
state和getters本质一样,都是数据源,都映射到组件的computed中
-
mutation和action区别:
相同点:
- 本质是一样的,都是函数
- 最多都接受两个形参(多个参数的话,传入对象格式),
- 都是映射到组件的methods中
不同点:
-
第一个形参不同
mutation 第一个形参是 state
action 第一个形参是 store
-
mutation函数放同步代码,action函数放同步代码