一、相关概述
-
组件之间共享数据(3种情况)
-
Vuex是什么
- Vuex存储数据
一般情况,只有组件之间共享数据,才有必要存储到Vuex中,对于组件中的私有数据,依旧存储在组建自身的data中
二、Vuex 基本使用
同时保证main.js引入store模块:
import store from ‘./store’
三、核心概念
//store的入口文件 index.js
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// 存放数据
count:0
},
mutations: {
// 变更store中的数据
add(state){
state.count++
}
},
actions: {
// context相当于当前store实例对象
addAsy(context){
//触发mutation
setTimeout(()=>{
context.commit('add')},1000)
}
},
Getter: {
showNum:state=>{
return '当前最新数据是['+state.count+']'
}
}
})
注:后面的代码按照以上store存储数据进行讲解
State
State提供唯一的公共数据源,所有共享数据都同意放到Store的State中存储
组件访问State中数据:
- 第一种方式:
// js 代码中
this.$store.state.全局数据名
// 模板中
{
{
$store.state.全局数据名 }}
- 第二种方式:
1.vuex 按需导入 mapState 函数
import {
mapState } from 'vuex'
2.将全局数据,映射为当前组件的计算属性
computed:{
...mapState(['count'])
}
Mutation
变更store中的数据
mutations: {
// 变更store中的数据 ,可以传参
addN(state, step){
state.count+=step
}
},
触发mutation
第一种方式:
methods:{
xxx() {
// step = 3
this.$store.commit('addN',3)
}
}
第二种方式:
// 1.vuex 按需导入 mapMutations 函数
import {
mapMutations } from 'vuex'
// 2.将指定mutation函数,映射为当前组件的method函数
method:{
...mapMutatuins(['addN','add'])
}
Action
用于处理异步任务
触发Action:
第一种方法:
actions: {
// context相当于当前store实例对象 可以传参数
addAsync(context,step){
//触发mutation
setTimeout(()=>{
context.commit('add',step)},1000)
}
},
method:{
xxx(){
this.$store.dispatch('addAsync',3)
}
}
第二种方法:
// 1.从vuex 按需导入 mapActions 函数
import {
mapActions } from 'vuex'
// 2.将指定actions函数,映射为当前组件的method函数
method:{
...mapActions(['addAsy','addAsync'])
}
Getter
用于包装Store中的数据,不更改数据,getter随着store数据改变而改变,类似于vue的计算属性
使用getter
第一种方法:
// this.$store.getters.名称
this.$store.getters.showNum
第二种方式:
// 1.从vuex 按需导入 mapGetters函数
import {
mapGetters } from 'vuex'
// 2.将指定Getters函数,映射为当前组件的计算属性:showNum
method:{
...mapGetters(['showNum'])
}
模板使用
{
{
showNum }}