Vuex核心内容梳理

Vuex官方链接

1、Vuex是干什么的

Vuex实现组件全局状态(数据)管理的一种机制,可以方便的实现组件间的数据共享

Vuex

2、Vuex的使用

store.js:

import { createStore } from "vuex";

export default createStore({
	state: {},
	mutations: {},
	actions: {},
	getters: {},
	modules: {},
});

(1)state:提供唯一的共享数据源

组件访问state调用方式一:

this.$store.state.全局变量名

组件访问state调用方式二:

// 1、从Vuex中引入mapState函数
import { mapState } from 'vuex'

// 2、将 state 中的全局变量,映射为当前组件的计算属性
computed:{
	...mapState(['全局变量名'])
}

(2)mutations:用于变更state中的数据

state中的数据只能通过mutations来变更,且不能在mutations中直接进行异步操作!!!

在mutations中定义函数的方法同methods
(注:函数第一个参数恒为state,可在第二个参数中传参)

调用方法

组件访问mutations调用方式一:

this.$store.commit('mutations中函数名')

组件访问mutations调用方式二:

// 1、从Vuex中引入mapMutations函数
import { mapMutations } from 'vuex'

// 2、将指定的 mutations 中的函数,映射为当前组件的 methods 函数
methods:{
	...mapMutations(['mutations中函数名'])
}

(3)actions:用于进行异步操作

// step为传递参数
actions: {
		异步函数名(context,step){
			setTimeout(()=>{
				context.commit('mutations中函数名',step);
			},1000)
		}
	},

组件访问actions调用方式一:

// step为传递参数
this.$store.dispatch('actions中异步函数名',step)

组件访问actions调用方式二:

// 1、从Vuex中引入mapActions函数
import { mapActions } from 'vuex'

// 2、将指定的 actions 中的函数,映射为当前组件的 methods 函数
methods:{
	...mapActions(['actions中异步函数名'])
}

(4)getters:用于包装 state 中的数据

state: {
    data: 0,
},
getters: {
    showData: (state) => {
      return "最新数据:" + state.data;
    }
},

组件访问getters调用方式一:

this.$store.getters.函数名

组件访问getters调用方式二:

// 1、从Vuex中引入mapGetters函数
import { mapGetters } from 'vuex'

// 2、将 getters 中的函数,映射为当前组件的计算属性
computed:{
	...mapGetters(['getters中函数名'])
}

(5)modules:模块化处理共享数据

将 store 分割成模块(module),每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NJR10byh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值