[Vuejs]-How to make a sum of value in data with Vue.js and use it in of v-if?

0👍

It’s difficult to give you a complete answer as I don’t know where quiz is coming from. Is it hardcoded or is it dynamic?

But either way, here is a method you can use to calculate the total value of the data:

const totalValue = quiz.reduce((total, item) => {
      const itemSum = item.responses.reduce((sum, response) => {
        return sum + response.value;
      }, 0);

      return total + itemSum;
  }, 0);

If the data is static then I would suggest just doing the calculation inside a created() hook and storing it in a data prop.

like:

data() {
    return {
        totalValue: 0
    }
},
created() {
    this.calculateValue();
},
methods: {
    calculateValue() {
        this.totalValue = quiz.reduce((total, item) => {
            const itemSum = item.responses.reduce((sum, response) => {
                return sum + response.value;
            }, 0);

            return total + itemSum;
        }, 0);
    }
}

and then your v-if is simply v-if="[1020, 1030, 1040, 1050].includes(totalValue)"

If quiz is more dynamic then you can try to use a computed method.

Leave a comment