[Vuejs]-How to Watch value in daynamique array in vuejs

0👍

Rather than watch and modify your data, you can use a computed property to return a new version of your list with the required items added. In general this tends to a bit less error prone and easier to understand. Here’s a working example:

<template>
  <div>
    <ul>
      <li v-for="(item, index) in itemsWithTotals" :key="index">
        <span>{{ item.total1 }} - {{ item.total2 }}</span>
      </li>
    </ul>
  </div>
</template>
const ITEMS = [
  { name: 'item1', price: 20, amount: 10, discount: 0 },
  { name: 'item2', price: 50, amount: 15, discount: 0.25 },
  { name: 'item3', price: 35, amount: 20, discount: 0.75 },
];

export default {
  data() {
    return { items: ITEMS };
  },
  computed: {
    itemsWithTotals() {
      return this.items.map(item => {
        const total1 = item.price * item.amount;
        const total2 = total1 * (1 - item.discount);
        return { ...item, total1, total2 };
      });
    },
  },
};

Note that I’ve converted your original data to have numeric properties, rather than strings.

Leave a comment