D
D
Denis2019-03-30 19:40:43
JavaScript
Denis, 2019-03-30 19:40:43

Vue.js cache data when rendering v-for list?

The page displays a list like this, it just has a quantity and buttons to add and subtract to the cart
, there are also navigation buttons that change the list of products in the cart and this list is loaded via ajax and simply replaced in a variable and vue renders it again

<div v-for="item in products">
      {{item.name}}
    <template  v-if="item.count==0">
     <button>Добавить в корзину</button>
 </template>
 <template v-else>
     <button @click="item.count--">-</button> {{item.count}} <button @click="item.count++">+</button>
 </template>
</div>

Everything works fine, for one thing, but when a new product list is called, Vue renders this product list and displays the new name of it in item.name, but item.count stops being reactive and stores the value of the previous product. Although I look in Dev tools Vue, the value changes correctly there, but rendering in the DOM does not work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grinat, 2019-03-30
@Virtus_pro

Vue does not cache, it builds a virtual house, compares it with the previous state, and if there are changes, it rebuilds the real one. In your case, most likely due to the fact that there are no keys, the diff breaks and vue decides that there are no changes, or you declare count somehow crookedly and it does not become reactive. Add keys and with ajax assign values ​​to products like: this.products = Object.assign({}, ajaxProducts) this should assign Vue reactive getters/setters to all object properties.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question