Saaransh Menon
Saaransh Menon

Reputation: 416

How to re render v-for when new keys are added to an object

I know that when adding new keys to an object that is used in a v-for wont trigger a change in v-for, but it is necessary for me to do. Is there any way I can do it?

My Code:

<v-col
   v-for="(product, key) in products"
   :key="key"
   cols="12"
   lg="4"
>
   <ProductsCard
      v-on:showDeleteDialog="showDeleteDialog($event)"
      :callback="updateSwitch"
      :product="product"
      :shareIcon="shareIcon"
      :menuIcon="menuIcon"
      :callBackMethods="callBackMethods"
   ></ProductsCard>
</v-col>

The function that brings new data from cloud firestore

async loadMoreProducts() {
   let lastVisible = this.initialProductsPromise.docs[
      this.initialProductsPromise.docs.length - 1
   ];
   let nextPromise = await getRemainingProducts(this.catId, lastVisible);
   if (!nextPromise.empty) {
      nextPromise.forEach(doc => {
         if (doc.exists) {
            this.products[doc.id] = {
              data: doc
            };
         }
      });
      this.initialProductsPromise = nextPromise;
   }
},

Update:

v-for="(product, key, index) in products"
   :key="index"
   cols="12"
   lg="4"

I changed the key to the index and used Dan's solution.

Upvotes: 1

Views: 622

Answers (1)

Dan
Dan

Reputation: 63059

You have to use Vue.set or this.$set:

if (doc.exists) {
   this.$set(this.products, doc.id, {
      data: doc
   });
}

From the docs:

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, propertyName, value) method

Upvotes: 1

Related Questions