您好,欢迎来到99网。
搜索
您的当前位置:首页整理vuex

整理vuex

来源:99网

mutation

mutation用于变更store中的数据
1、只能通过mutation变更store数据,不可以直接操作store中的数据。

this.$store.state.count++ //不允许这种操作

2、通过mutation这种方式,可以集中监控所有数据的变化
想要改变count的值,可以:

const store = new Vuex.store({
	state: {
		count: 0
	},
	// 只有mutations中定义的函数,才有权利修改state中的数据
	mutations: {
		add(state) {
			//变更状态
			state.count++
		}
	}
})

在组件中可以调用函数,进行使用

methods: {
	handle() {
		// commit的作用就是调用某个 mutation 函数
		this.$store.commit('add')
	}
}

如何在触发mutations时传递参数:

const store = new Vuex.store({
	state: {
		count: 0
	},
	mutations: {
		addN(state, step) {
			//变更状态
			state.count += step
		}
	}
})
methods: {
	handle() {
		// 携带参数
		this.$store.commit('addN',3)
	}
}

this.$store.commit()是出发mutations的一种方式,还有第二种方式:

1、从vuex中按需导入mapMuations 函数
import { 'mapMutations' } from 'vuex'

通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法

2、将指定的mapMutations函数,映射为当前组件的methods函数
methods: {
	...mapMutations(['add','addN'])
	handle() {
		this.add() 直接调用映射过来的mutation函数
	}
}

不要在mutations函数中,执行异步操作,

action

action用于处理异步任务
如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是action中还是要通过触发mutation的方式间接变更数据。

const store = new Vuex.store({
	state: {
		count: 0
	},
	mutations: {
		add(state) {
			//变更状态
			state.count ++
		}
	},
	actions: {
		// 在action中,不能直接修改state中的数据
		// 必须通过context.commit()触发某个mutation才可以
		addAsync(context) {
			setTimeout(() => {
				context.commit('add')
			},1000)
		}
	}
})

组件中,触发action,第一种方式:

methods: {
	handle () {
		// 触发actions的第一种方式
		// 这里的dispatch函数,专门用于触发 actions中的函数
		this.$store.dispatch('addAsync')
	}
}

第二种:
1、从vuex中按需导入mapActions 函数

import { 'mapActions' } from 'vuex'

通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法

2、将指定的mapActions函数,映射为当前组件的methods函数
methods: {
	...mapActions(['addAsync'])
	handle() {
		this.addAsync() 直接调用映射过来的actions函数
	}
}

如何触发actions异步任务是携带参数:

const store = new Vuex.store({
	state: {
		count: 0
	},
	mutations: {
		addN(state, step) {
			state.count += step
		}
	},
	actions: {
		addAsync(context,step) {
			setTimeout(() => {
				context.commit('addN',step)
			},1000)
		}
	}
})

触发action

methods: {
	handle () {
		this.$store.dispatch('addAsync', 5)
	}
}
getter

getter用于对store中的数据进行加工处理形成新的数据。getter不会改变state中的数据,只是加工包装
1、getter可以对store中已有的数据加工处理之后形成新的数据,类似vue的计算属性。
2、store中数据发生变化,getter的数据也会跟着变化。

const store = new Vuex.Store({
	state: {
		count: 0
	},
	getters: {
		showNum(state): {
			return '当前最新的数据是'+ state.count
		}
	}
})

使用getters的第一种方式:

this.$store.getters.showNum

第二种方式:

import { mapGetters } from 'vuex'

computed: {
	...mapGetters({'showNum'})
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 99spj.com 版权所有 湘ICP备2022005869号-5

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务