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

vuex入门(四)

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