...mapActions(['login']) 是 Vuex 的语法,用于在组件中映射 Vuex 的 actions 方法 ,让你可以像调用本地方法一样去调用 Vuex 中的 login 方法。
它的意思是:
js
...mapActions(['login'])
等价于:
js
methods: {
login() {
return this.$store.dispatch('login');
}
}
使用场景:
在 Vue 组件的 methods 中使用 mapActions:
js
<script>
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions(['login']),
}
}
</script>
然后你就可以在组件里直接调用:
js
this.login(); // 实际上是触发 Vuex 里的 login action
举个实际例子:
Vuex 中:
js
// store.js
export default {
actions: {
login({ commit }, payload) {
// 做登录逻辑,比如发请求
console.log('用户登录中...', payload);
}
}
}
组件中:
js
export default {
methods: {
...mapActions(['login']),
doLogin() {
this.login({ username: 'test', password: '123456' });
}
}
}
补充:mapActions 的作用
| 用法 | 作用 |
|---|---|
mapActions(['xxx']) |
映射 this.xxx() 到 Vuex action |
mapMutations(['xxx']) |
映射 this.xxx() 到 Vuex mutation |
mapState(['xxx']) |
映射 Vuex state 到组件计算属性 |