展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

vuex入门(三)

  • 在store的mutations函数中不能执行异步操作,例如不能使用setTimeout()方法

  • 只有mutations才能操作state中的数据,只有actions才能操作mutations中的方法

  • actions操作mutations中的函数,方式1

// store
import { createStore } from 'vuex'
export default createStore({
state: {
count: 0
},
mutations: {
add(state) {
state.count++;
}
},
actions: { // 异步调用mutations中的函数
addAsync(context){ // context表示store实例
setTimeout(function(){
context.commit('add') // 2秒后commit调用mutations中方法
},2000)
}
},
modules: {
}
})
// 子组件中通过dispatch方法调用store的actions中的函数
<template>
<div>
<button @click="btnHandler3">+1_Async</button>
</div>
</template>
<script>
export default {
methods: {
btnHandler3() {
// dispatch方法用于触发actions中函数
this.$store.dispatch('addAsync')
}
}
}
</script>
  • actions异步调用,同时传参
// store
import { createStore } from 'vuex'
export default createStore({
state: {
count: 0
},
mutations: {
addN(state, step) {
state.count += step;
}
},
actions: {
addNAsync(context, step) {
setTimeout(function(){
context.commit('addN', step) // 传入参数
}, 2000);
}
},
modules: {
}
})
// 子组件Addition中调用acitons中的方法,同时传入参数5
<template>
<div>
<button @click="btnHandler4">+N_Async</button>
</div>
</template>
<script>
export default {
methods: {
btnHandler4() {
this.$store.dispatch('addNAsync', 5)
}
}
}
</script>
  • actions异步调用mutations中的函数,方式2
// store
import { createStore } from 'vuex'
export default createStore({
state: {
count: 0
},
mutations: {
sub(state) {
state.count--;
}
},
actions: {
subAsync(context){ // 参数为store实例
setTimeout(function(){
context.commit('sub') // 2秒后调用mutations中的函数
}, 2000);
}
},
modules: {
}
})
// 子组件Subtraction中,引入mapActions函数
<script>
import { mapActions } from "vuex";
export default {
methods: {
// 使用mapActions函数将store中的subAsync函数映射到该子组件
...mapActions(['subAsync']),
btnHandler3() {
this.subAsync(); // 映射到该子组件后,直接调用
}
}
};
</script>
posted @   DogLeftover  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示