之前也讲过了,actions中是用来操作异步代码的,由于在mutations写异步操作会导致devtools工具记录不到state的变化,因此才有actions的存在,下面是基本的使用,如下:点击按钮,发布到actions:templatedivbut...

之前也讲过了,actions中是用来操作异步代码的,由于在mutations写异步操作会导致devtools工具记录不到state的变化,因此才有actions的存在,下面是基本的使用,如下:
点击按钮,发布到actions:
<template> <div> <button @click="toAjax">发起异步请求</button> </div> </template> methods: { toAjax(){ this.$store.dispatch('sendAjax') } }
定义sendAjax,并提交到mutations:
mutations: { msendAjax(state){ state.counter++ } } actions: { sendAjax(context){ //异步操作 setTimeout(()=>{ context.commit('msendAjax') },1000) } }
上面的context对象相当于state,拥有一些和state相同的方法。上面只是基本的使用,如果在dispatch要传递参数,和commit传递参数要怎么做呢?如下:
methods: { toAjax(){ const arg = '我是参数' this.$store.dispatch('sendAjax',arg) } }
mutations: { msendAjax(state,payload){ console.log(payload) state.counter++ } }, actions: { sendAjax(context,arg){ setTimeout(()=>{ context.commit('msendAjax',arg) },1000) } }
上面是actions无参和有参的基本使用了。但实际开发中,在actions中方法执行完毕了,要给componnet返回结果告诉操作已经完成,那该如何做呢? 如下:
<template> <div> <button @click="toAjax">发起异步请求</button> </div> </template>
methods: { toAjax(){ const arg = '我是参数' this.$store .dispatch('sendAjax',arg) .then(() => { console.log('dispatch已经完成了') }) } }
mutations: { msendAjax(state,payload){ console.log(payload) state.counter++ } }, actions: { sendAjax(context,arg){ return new Promise(resolve => { setTimeout(()=>{ context.commit('msendAjax',arg) resolve() },1000) }) } }
参数该怎么传还怎么传,原本的异步代码用 new Promise包裹起来,然后.then不要在actions中写,在components写会比较明显易懂
本文标题为:vue-vuex-actions的基本使用


基础教程推荐
- 原生ajax瀑布流demo分享(必看篇) 2023-02-01
- JavaScript垃圾回收机制(引用计数,标记清除,性能优 2022-08-31
- Ajax提交表单并接收json实例代码 2023-02-13
- 在IE中为abbr标签加样式 2022-10-16
- Unicode中的常用字母小结 2022-09-21
- 解决:layUI数据表格+简单查询 2022-12-16
- ajax实现数据分页查询 2023-01-31
- 纯javascript的ajax实现php异步提交表单的简单实例 2022-12-28
- 关于ajax异步访问数据的问题 2023-02-23
- AJax 把拿到的后台数据在页面中渲染的实例 2023-02-22