Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a new property to array of object inside v-for - Vue.js

Tags:

vue.js

vuejs2

I want to add on extra property(showMore) dynamically to array of object inside v-for. is it possible to do it inside v-for like:

this.students = [
{
 name: 'anonymous',
 class: 'Sixth',
 otherInfo: "..."
},
{
 name: 'anonymous2',
 class: 'Sixth',
 otherInfo: "..."
}
]
<div v-for="student in students">
  <div>{{student.name}}</div>
  <div>{{student.class}}</div>
  <div @click="student.showMore = true">Show more +</div> 
  <!-- it was possible in angularjs. is it possible in vuejs ?-->
</div>

here i am adding one more property (showMore) to array of object(student) by clicking on Show more. is it possible inside v-for? if not then how to achieve this(with best practice)?

like image 827
Mukund Kumar Avatar asked Nov 01 '17 10:11

Mukund Kumar


People also ask

Is it possible to add new properties to a Javascript object dynamically?

Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} . Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time.

How do I add elements to an array in Vue?

Add Element to Array With push() Method To add an element to an array in Vue, call the push() method in the array with the element as an argument. The push() method will add the element to the end of the array. Clicking the button adds a new fruit element.

How do I create a dynamic reference in Vue?

Simply use v-bind like :ref="'element' + result.id" or ref="`element${result.id}`" .


1 Answers

Sure, but it will not be reactive though. If you want that, you need to use:

vm.$set( target, key, value )

https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

like image 133
Stephan-v Avatar answered Oct 03 '22 12:10

Stephan-v