我有一个由
呈现的简单组件<House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House>
该组件看起来像
<template>
<div class="house">
<ul>
<li v-for="person in people">
{{ person.name }}
</li>
</ul>
<a href="#add" @click="addMark">Add Mark</a>
</div>
</template>
<script>
export default {
props: ['_people'],
data: function(){
return {
people: this._people
}
},
methods: {
addMark: function(){
this.people.push({
name: 'Mark'
});
}
},
}
问题是我必须将json有效负载传递给初始组件,但这会将有效负载设置为prop,而不是数据属性。如果我试图操纵道具,它永远不会更新。所以我将_people prop映射到了people属性。
这是个好主意吗?我在这里错过了一些明显的东西吗?
答案 0 :(得分:1)
传递一个对象作为道具:
people = {
list: [{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]
}
<House :_people="people"></House>
然后
props: ['_people'],
methods: {
addMark() {
this._people.list.push({
name: 'Mark'
})
}
}
答案 1 :(得分:1)
您可以使用计算属性:
export default {
props: ['_people'],
data() {
return {
added: false
}
},
computed: {
people() {
var _arr = this._people.slice();
return this.added ? _arr : _arr.push({ name: 'Mark' });
}
},
methods: {
addMark: function(){
this.added = true
}
},
}