网络编程
位置:首页>> 网络编程>> JavaScript>> vuex新手进阶篇之actions的使用方法

vuex新手进阶篇之actions的使用方法

作者:Jay丶千珏  发布时间:2024-04-27 16:13:54 

标签:vuex,actions

紧接上篇文章,本篇文章讲vuex ,如何去改变state ,actions的使用,我依然使用了vuex的modules

1.设置actions事件

index.js

vuex新手进阶篇之actions的使用方法

dict.js

vuex新手进阶篇之actions的使用方法

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")
   }
 }

 

来源:https://blog.csdn.net/qq_42543244/article/details/118225352

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com