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.

JavaScript

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

I have tried as follows:

JavaScript

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

JavaScript

or ternary

JavaScript

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:

JavaScript

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

Commits would look like this:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement