之前也讲过了,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的基本使用
- 1 Vue - 简介 2023-10-08
- JS实现左侧菜单工具栏 2022-08-31
- layui数据表格以及传数据方式 2022-12-13
- 深入浅析AjaxFileUpload实现单个文件的 Ajax 文件上传库 2022-12-15
- 关于 html:如何从 css 表中删除边距和填充 2022-09-21
- jsPlumb+vue创建字段映射关系 2023-10-08
- javascript 判断当前浏览器版本并判断ie版本 2023-08-08
- 基于CORS实现WebApi Ajax 跨域请求解决方法 2023-02-14
- vue keep-alive 2023-10-08
- ajax实现输入提示效果 2023-02-14
