之前也讲过了,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的基本使用


基础教程推荐
- Loaders.css免费开源加载动画框架介绍 2025-01-23
- Django操作cookie的实现 2024-04-15
- clientX,pageX,offsetX,x,layerX,screenX,offsetLeft区别分析 2024-01-08
- js判断一个对象是否在一个对象数组中(场景分析) 2022-10-21
- webpack学习笔记一:安装webpack、webpack-dev-server、内存加载js和html文件、loader处理非js文件 2023-10-29
- JSONObject与JSONArray使用方法解析 2024-02-07
- 创建Vue3.0需要安装哪些脚手架 2025-01-16
- 纯css实现漂亮又健壮的tooltip的方法 2024-01-23
- Bootstrap学习笔记之css组件(3) 2024-01-22
- html5视频如何嵌入到网页(视频代码) 2025-01-22