Skip to content
Advertisement

How you can have a dynamic operation in vue

Hello I have a method that modifies a state of vuex, the main function of the method is to add or subtract to a state of vuex.

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

But I need to pass the -- o ++ to it dynamically, how can I achieve this?

I have tried as follows:

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

But I don’t get the result, any idea how I can do this dynamically?

Advertisement

Answer

Pass a boolean instead of the operation and then use either an if statement

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

or ternary

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

I should note, that this isn’t the standard approach in Vuex. Mutations should always only have one side effect. You should have a mutation to decrement and a mutation to increment.

Then you can combine the two like in the above example using a dispatched method in your Vuex store.

You can also instead commit the step amount:

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

if step amount is a negative, it will decrement. If it is positive, it will increment.

Commits would look like this:

commit('setStep', -1);
commit('setStep', 5);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement