我想在v-for中动态添加额外属性(showMore
)到对象数组。是否可以在v-for
内完成:
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>
这里我通过点击Show more将一个属性(showMore
)添加到对象数组(student
)。是否有可能在v-for内?如果没有那么如何实现这一目标(最佳实践)?
答案 0 :(得分:5)
当然,但它不会被动反应。如果你想要,你需要使用:
vm.$set( target, key, value )
https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
答案 1 :(得分:1)
使用Vue.set(obj, property, value);
详细示例:
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="showMore(student)">Show more +</div>
<!-- it was possible in angularjs. is it possible in vuejs ?-->
</div>
showMore(student) {
Vue.set(student, 'showMore', true);
}
注意:不要忘记导入Vue
答案 2 :(得分:-1)
如果您定位的是现代浏览器,则可以始终使用摘要标记:
<details>
<summary>More Info</summary>
<p>hello!</p>
</details>