Vue.component ('app-hous', {
data: function () {
return {
message: 'Hello world, hello',
houses: [
{name: "HILL8"},
{name: "HILL12"},
]
}
},
computed: {
showMess () {
return 'Get presentation ' + this.hous.name
},
},
template: `
<div><div class="houses" v-for="hous in houses">
<div class="plan">
<div>{{ hous.name }} </div>
<div>{{ showMess }} </div>
</div>
</div></div>`
});
new Vue({
el: '#app',
data: {
styleCSS: "",
value: 1,
},
});
我需要计算对象houses
的元素。但我在v-for="hous in houses"
之前运行它,所以我无法获得showMess。我该怎么修?
https://jsfiddle.net/Nata_Hamster/p43o8d69/
在这种情况下不应该使用计算变量。
只需使用一种方法:
methods: {
showMess(houseName) {
return 'Get presentation ' + houseName;
}
}
然后在您的模板中:
template: `
<div><div class="houses" v-for="hous in houses">
<div class="plan">
<div>{{ hous.name }} </div>
<div>{{ showMess(hous.name) }} </div>
</div>
</div>
</div>
`
计算属性旨在对变量应用简单的操作。但是,在您的情况下,hous
变量不直接在数据上,它是数据中houses
的一个元素。
下面是一个计算属性的例子,它可以完成同样的事情,但我仍然建议您使用上面的方法示例:
computed: {
messByHouseName() {
const messByHouseName = {};
for (const house of this.houses) {
messByHouseName[house.name] = `Get presentation ${house.name}`;
}
return messByHouseName;
}
}
然后在您的模板中:
template: `
<div><div class="houses" v-for="hous in houses">
<div class="plan">
<div>{{ hous.name }} </div>
<div>{{ messByHouseName[hous.name] }} </div>
</div>
</div>
</div>
`
计算的属性不会自动循环到您的房子上。你有两种方法可以做到这一点。您可以创建一个方法(如本答案所述:https://stackoverflow.com/a/67773527/11011360)或者创建具有所需输出的计算属性(编辑:Catalin Hoha也展示了使用计算属性实现这一点的方法,但方法不同(:
convertedHouses() {
const converted = houses.map(hous => {
return {
...hous, // or you could write "name: hous.name" instead
message: 'Get presentation ' + hous.name
}
});
return converted;
}
并访问模板中的计算属性:
template: `
<div class="houses" v-for="hous in convertedHouses">
<div class="plan">
<div>{{ hous.name }} </div>
<div>{{ hous.message }} </div>
</div>
</div>
`