vuex 简述

1 篇文章 0 订阅

vuex 解决了组件以及路由之间相互通讯和实时更新的问题

1. State

state 提供统一公告资源,所有公共的变量可以放在 state 中存储

// 声明全局变量
const store = new Vuex.Store({
	state: { count: 0 }
})
/**
 * 调用全局变量
 * 方法一: this.$store.state 调用
 */ 
this.$store.state.count // this 指向全局 vue 实例
/**
 * 方法二: mapState API
 */
import { mapState } from 'vuex'
computed: {
	...mapState(['count'])
}

2. Mutation

Mutation 用来修改 state 中的值,注意,不能直接修改 state 中的值,需要调用 Mutation

// 声明全局变量 以及对应 Mutatiaon
const store = new Vuex.Store({
	state: { count: 0 },
	mutations: {
		add(state, data) {
			// 可以通过 state 取到变量的值
			// data 是传递的参数
			state.count = data
		}
	},
})
// 触发方法
this.$store.commit('count', 1)
// mapMutations API
import { mapMutations } from 'vuex'
methods: {
	...mapMutations(['add']),
	vuexAdd () {
		// 直接调用并传参即可
		this.add(1)
	}
}

2. Mutation

Mutation 用来修改 state 中的值,注意,不能直接修改 state 中的值,需要调用 Mutation

// 声明全局变量 以及对应 Mutatiaon
const store = new Vuex.Store({
	state: { count: 0 },
	mutations: {
		add(state, data) {
			// 可以通过 state 取到变量的值
			// data 是传递的参数
			state.count = data
		}
	},
})
// 触发方法一
this.$store.commit('count', 1)
// 触发方法二
import { mapMutations } from 'vuex'
methods: {
	...mapMutations(['add']),
	vuexAdd () {
		// 直接调用并传参即可
		this.add(1)
	}
}

注意: 此方法中不能有异步操作

3. Action

Action 用于解决 Mutation 中的异步操作

// 声明全局变量 以及对应 Mutatiaon、Action
const store = new Vuex.Store({
	state: { count: 0 },
	mutations: {
		add(state, data) { state.count = data }
	},
	actions: {
		addAsync (context, step) {
			setTimeout(() => {
				// 通过调用 mutations 中定义的方法,来实现异步修改 state
				context.commit('add', step)
			}, 1000)
		}
	}
})
// 触发方法一
this.$store.dispatch('addAsync', 1)
// 触发方法二
import { mapActions } from 'vuex'
methods: {
	...mapActions(['addAsync']),
	vuexAdd () {
		// 直接调用并传参即可
		this.addAsync('add', 1)
	}
}

4. Getter

Getter 可以讲 state 中的变量,包装成新的数据形式

// 声明全局变量 以及对应 Getter
const store = new Vuex.Store({
	state: { count: 0 },
	Getter: {
		showCount(state) {
			return '当前的最新 count 是' + state.count
		}
	}
})
// 获取方法一
this.$store.getters.showCount
// 获取方法二
import { mapGetters } from 'vuex'
computed: {
	...mapGetters (['showCount']),
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值