深刻认识this.$store.dispatch() 与 this.$store.commit()的区别

关于这个问题,我写博客之前已经在网上查过很多博客。但是,回答很多都很笼统,不怎么清楚。
下面来看一下我的理解。
commit: 同步操作
存储

this.$store.commit('changeValue',name)

取值

this.$store.state.changeValue

dispatch: 异步操作
存储

this.$store.dispatch('getlists',name)

取值

this.$store.getters.getlists

总的来说,他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state

`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、付费专栏及课程。

余额充值