如何在vue中进行动态操作



你好,我有一个修改vuex状态的方法,该方法的主要功能是对vuex状态进行加法或减法运算。

setStep(state, type) {
state.currentStep++;
}

但是我需要动态地将--++传递给它,我该如何实现呢?

我试过如下:

setStep(state, type = ++ or --) {
state.currentStep[type];
}

但我没有得到结果,你知道我如何动态地做到这一点吗?

传递布尔值而不是运算,然后使用if语句

setStep(state, increment) {
if (increment) {
state.currentStep++;
} else {
state.currentStep--;
}
}

或三元

setStep(state, increment) {
increment ? state.currentStep++ : state.currentStep--;
}

我应该注意,这不是Vuex中的标准方法。突变应该总是只有一个副作用。你应该有一个减少的突变和一个增加的突变。

然后,您可以像上面的例子一样,在Vuex商店中使用dispatched方法将两者结合起来。

您也可以提交步数:

setStep(state, stepAmount) {
state.currentStep += stepAmount
}

如果阶跃量为负数,它将递减。如果它是正的,它将递增。

委员会看起来是这样的:

commit('setStep', -1);
commit('setStep', 5);

您需要有两个函数incrementdecrement,您可以根据需要选择调用其中一个。

const app = new Vue({
el: "#app",
data() {
return {
step: 0
}
},
methods: {
updateStep(incrementor) {
this.step += incrementor;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="updateStep(-1)">--</button>
<span>{{step}}</span>
<button @click="updateStep(1)">++</button>
</div>

最新更新