vuex action参数(vuex新手进阶篇之actions的使用方法)
导读:紧接上篇文章,本篇文章讲vuex ,如何去改变state ,actions的使用,我依然使用了vuex的modules...
紧接上篇文章,本篇文章讲vuex ,如何去改变state ,actions的使用,我依然使用了vuex的modules
1.设置actions事件
index.js
dict.js
2.在组件中去分发actions
<template>
<div>
<div>
改变vuex index.js 下的state
<div>
{{ $store.state.userInfo.name + "---" + $store.state.userInfo.age }}
</div>
<div>
<button @click="changeUserInfo">修改方式1</button>
</div>
<div>
<button @click="changeUserInfo2">修改方式2</button>
</div>
</div>
--------------------------------------------------
<div>
改变vuex index.js modules下的dict 下的state
<div>
{{ $store.state.dict.taskTypeDict }}
</div>
<div>
<button @click="changeDict">修改方式1</button>
</div>
<div>
<button @click="changeDict2">修改方式2</button>
</div>
</div>
</div>
</template>
<script>
import { mapActions } from "vuex"; //方式二 1.首先引入
export default {
methods: {
// 方式一,dispatch分发事件
changeUserInfo() {
this.$store.dispatch("getUserInfo");
},
// 方式二
...mapActions(["getUserInfo2"]), //2.使用mapActions函数将组件的 methods 映射为 store.dispatch 调用
changeUserInfo2() {
this.getUserInfo2(); //3.调用
},
// -------------------------------------------------------------------------------------------
//因为我们在modules下开启了命名空间,所以我们在调用dict下的Actions时,需在前方加上空间名字
changeDict() {
this.$store.dispatch("dict/getTaskTypeDict");
},
//因为我们开辟了命名空间,故需要重写一个方法名,进行承接映射,注意此处不再是数组,而是一个对象
...mapActions({ getDicts: "dict/getTaskTypeDict2" }),
changeDict2() {
this.getDicts();
},
},
};
</script>
3.注意点
action 类似于 mutation,不同在于
1.action 提交的是 mutation事件,而不是直接去改变state的状态值,改变state的值只有通过mutation
2.action 可以包含任意异步操作
actions的细节补充
1.参数问题
2.context的其他属性
3.另外一种提交风格(见上以对象的形式进行分发)
//store的index.js中
actions: {
// 放函数
// 1.参数问题
incrementAction(context, payload) {
console.log(payload)
setTimeout(() => {
context.commit(increment)
}, 1000);
},
// 2.context的其他属性
decrementAction({ commit, dispatch, state, rootState, getters, rootGetters }) {
commit("decrement")
}
}
总结
到此这篇关于vuex新手进阶篇之actions使用的文章就介绍到这了,更多相关vuex actions的使用内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!