-1

In my Vue application, I have an array of stocks:

stocks : [
    {'name' : 'Tesla', 'price' : 800},
    {'name' : 'Microsoft', 'price' : 300},
]

I also have a conditional element that looks like this:

<template v-for="stock in stocks">
    <div>{{ stock.name }}</div>
    <div v-if="stock.hasOwnProperty('test')">test</div>
</template>

I have a method that sets the test property for a stock. For example:

this.stocks[0].test = true;

If, under this statement, I console.log(this.stocks) I see the test property for the first stock. But, in the template, the element that is supposed to show up when a stock has this property still doesn't show up. Why is this and how can I achieve showing/hiding stock elements dynamically based on whether they have the test property?

sveti petar
  • 3,637
  • 13
  • 67
  • 144
  • 1
    Vue doesn't detect the change; you have to a) use `this.$forceUpdate();` or b) use a key for the list items that changes –  Apr 28 '21 at 10:35

1 Answers1

1

Vue (2, anyway) cannot detect property addition or removal.

You should declare the test property within stocks, so that it's there from the beginning:

stocks : [
    {'name' : 'Tesla', 'price' : 800, test: false },
    {'name' : 'Microsoft', 'price' : 300, test: false },
]

Then it'll be reactive and you can show/hide your element based on the value of test.

Brother Woodrow
  • 6,092
  • 3
  • 18
  • 20