Home > Back-end >  Why nested array dynamic update is not working in my case
Why nested array dynamic update is not working in my case

Time:01-23

Hi i have a problem with nested array dynamic update as shown in below image

enter image description here

Here is a steps to re-produce the problem

  1. click on Add Likes button it will add likes for eg New Apple
  2. my default like is Mango
  3. click on Add about button it will add next row (Mango is not appeared) click on Add Likes to see the problem.

For reducing code readability i have put helper function into a mixin file called mixin.js

Expectation: i can add any number of Add about and Add Likes(with default value Mango)

Here is my code: https://codesandbox.io/s/musing-hawking-di4d3?file=/src/App.vue

CodePudding user response:

First, you don't need a nested array for the tags property. Use:

getLikesTemplate() {
  let year = this.year;
  let template = {
    id: this.getUniqueId(),
    like: `I'm ${year} Old and like things like`,
    tags: [this.getTagsTemplate("Mango")]          //nesting removed
  };
  this.year  ;
  return template;
}

Secondly, in JS objects are passed by reference, so you can do this:

method:

addLikes(like) {                                   //removed the extra code
  like.tags.push(this.getTagsTemplate("New Apple"));
},

template:

... 
<div style="text-align: left; display: flex">
  <div>                               //nesting removed
    <div  v-for="tag in like.tags" :key="tag.id">    
      {{ tag.name }}
    </div>
  </div>                              //passing the reference to the object
  <button style="margin-left: 20px" @click="addLikes(like)">
    Add Likes
  </button>
</div>

Result img

  •  Tags:  
  • Related