Vue学习-this.$store.dispatch()/commit()异同

本文详细介绍了Vue框架中状态管理工具Vuex的使用方法,包括如何通过commit和dispatch进行值的存取操作。同时对比了两者之间的区别,如commit为同步操作,而dispatch则适用于异步操作。

一、相同

都可以用于存取值

 this.$store.commit('key',val)【存值】
 this.$store.state.key【取值】

例:
存:

 findAllMenuTree().then((res)=>{
   if(res.code == 200){
       this.$store.commit("setMenu", {
              menuData: res.result
       });
 }})

取:

this.$store.state.menuData;

在这里插入图片描述

this.$store.dispatch('key',val)【存值】
this.$store.getters.key【取值】

二、不同

commit:同步操作,写法:this.$store.commit(‘mutations方法名’,值)

dispatch:异步操作,写法:this.$store.dispatch(‘actions方法名’,值)
在store中定义了mutations和actions
在这里插入图片描述

`this.$store.dispatch('updateLiveAppList', this.$router)` 是 Vuex 中用于触发异步操作的方法调用。 ### 使用场景与含义 在 Vuex 里,`this.$store.dispatch` 一般用来触发一个 action。在代码 `this.$store.dispatch('updateLiveAppList', this.$router)` 中,`'updateLiveAppList'` 是要触发的 action 的名称,`this.$router` 则是传递给该 action 的参数。通常,action 可包含异步操作,像发送网络请求、处理定时器等,还可以在 action 里提交 mutation 来更改 store 中的 state。 ### 示例代码 #### 定义 action ```javascript // store/index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { liveAppList: [] }, mutations: { UPDATE_LIVE_APP_LIST(state, newList) { state.liveAppList = newList; } }, actions: { updateLiveAppList({ commit }, router) { // 这里可以进行异步操作,例如根据路由信息获取数据 // 假设通过路由信息获取新的直播应用列表 const newList = getLiveAppListBasedOnRoute(router); commit('UPDATE_LIVE_APP_LIST', newList); } } }); function getLiveAppListBasedOnRoute(router) { // 模拟根据路由信息获取数据 return ['app1', 'app2', 'app3']; } ``` #### 在组件中使用 ```vue <template> <div> <!-- 组件内容 --> </div> </template> <script> export default { methods: { updateList() { this.$store.dispatch('updateLiveAppList', this.$router); } }, mounted() { this.updateList(); } }; </script> ``` ### 常见报错及解决办法 - **action 未定义**:若出现 `[vuex] unknown action type: updateLiveAppList` 错误,表明在 store 里未定义 `updateLiveAppList` 这个 action。需要检查 store 中的 `actions` 对象,保证 `updateLiveAppList` 已正确定义。 - **异步操作未处理**:当 action 里的异步操作(如网络请求)失败时,可能会引发错误。可以在 action 里使用 `try...catch` 来捕获错误并处理,或者在组件中使用 `.catch()` 方法处理错误。 ```javascript this.$store.dispatch('updateLiveAppList', this.$router) .catch(error => { console.error('更新直播应用列表失败:', error); }); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值