web前端全系列 教程
1839个小节阅读:2242.9k
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
你可以向 store.commit
传入额外的参数,即 mutation 的载荷(payload)
xxxxxxxxxx
import { createStore } from 'vuex'
const store = createStore({
state:{
count: 10
},
getters: {
getCount(state) {
return "当前Count值为: "+state.count;
}
},
mutations:{
increment(state,num){
state.count += Number(num)
},
decrement(state,num){
state.count -= Number(num)
}
}
})
export default store
xxxxxxxxxx
<template>
<h3>Nums</h3>
<p></p>
<input type="text" v-model="num">
<button @click="addHandler">增加</button>
<button @click="minHandler">减少</button>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
data(){
return{
num:""
}
},
computed:{
mapGetters(["getCount"])
},
methods:{
addHandler(){
this.$store.commit("increment",this.num)
},
minHandler(){
this.$store.commit("decrement",this.num)
}
}
}
</script>
xxxxxxxxxx
<template>
<h3>Count</h3>
<p></p>
<input type="text" v-model="num">
<button @click="addHandler">增加</button>
<button @click="minHandler">减少</button>
</template>
<script setup>
import { computed,ref } from 'vue'
import { useStore } from 'vuex'
const num = ref("")
const store = useStore()
const currentCount = computed(() => {
return store.getters.getCount
})
function addHandler(){
store.commit("increment",num.value)
}
function minHandler(){
store.commit("decrement",num.value)
}
</script>
xxxxxxxxxx
this.$store.commit({
type:"increment",
num:this.num
})
当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数
xxxxxxxxxx
increment(state,{num}){
state.count += Number(num)
}
一条重要的原则就是要记住 mutation 必须是同步函数
现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的