vuex中mapActions的概念及用法

概念

先看一下官方文档对mapActions的描述:
在这里插入图片描述

简单来说 mapActions 就是将组件中的函数映射为对应的action

一般情况下我们会在组件中使用 this.$store.dispatch() 来触发 action ,想要调用多少个 action 就需要调用多少次 dispatch() ,而使用 mapActions 的话只需要往 mapActions 中传入与 action 同名的函数,然后调用这些函数即可触发对应的action

用法

了解了 mapActions 大概是用来干什么的之后,下面来介绍一下 mapActions 的具体用法

1、首先在vuex配置文件中定义要使用的 action :

actions: {
    
    
	login: function(context,data1) {
    
    
		console.log(data1)
	},
	exit: function(context,data2) {
    
    
		console.log(data2)
	}
}

2、在组件中引入并调用 mapActions ,然后通过调用 mapActions 中的函数的来触发 action :

<script>

import {
    
    mapActions} from "vuex" //引入mapActions

export default {
    
    
	data(){
    
    
		return{
    
    }
	}
	created(){
    
    
		// 调用函数触发action
		this.login('登录') //登录
		this.exit('退出') //退出
	}.
	methods:{
    
    
    	...mapActions(['login','exit']),
	}
}

</script>

猜你喜欢

转载自blog.csdn.net/jiangjunyuan168/article/details/126962600