英文:
I can display data through a method, but not through a computed property. Why?
问题
我有一个名为 "Hotels" 的数组属性,其中包含一个嵌套的酒店数组,其中包含各种值,如房间数量。为了显示这些值,我有一个数组,其中存储了一个图标、一个名称和一个函数。该函数在一个方法中调用,然后我使用 v-for
循环遍历该数组。
问题在于,我希望该数组具有响应性,所以我尝试将方法移到一个计算属性中,但这样做后,我的数据不再显示出来。我漏掉了什么?
这是模板内容:
<ul class="mb-2">
<li class="list-group-item mb-1">
</li>
<template v-for="(item, index) in facilities">
<li :key="index" v-if="item.function != null">
<i :class="item.iconClass"></i>
{{ item.name }}
<strong class="ml-2"> {{ item.function }} </strong>
</li>
</template>
</ul>
脚本部分:
<script>
export default {
props: {
hotels: Array,
},
data() {
return {
facilities: [
{
iconClass: "fas fa-door-open fa-fw fa-lg icon-class ml-2 mr-2",
name: 'Number of rooms:',
function: this.numberOfRooms,
}
],
}
},
computed: {
numberOfRooms(){
if(this.hotels[0].hotel.numberRooms > 0) {
return this.hotels[0].hotel.numberRooms
}
},
}
}
</script>
请注意,我只进行了代码的翻译,没有添加其他内容。
英文:
I have an array prop "Hotels", which consists of a nested array of hotels, which consists of various values, such as number of rooms.
To show the values, I have an array which stores an icon, a name and a function. The function is called in a method and then I loop through the array with v-for.
The problem is that I would like for the array to be reactive, so I tried moving the method into a computed property, but when doing so my data will no longer display.
What am I missing?
This is the template content:
<ul class="mb-2">
<li class="list-group-item mb-1">
</li>
<template v-for="(item, index) in facilities">
<li :key="index" v-if="item.function != null">
<i :class="item.iconClass"></i>
{{ item.name }}
<strong class="ml-2"> {{ item.function }} </strong>
</li>
</template>
</ul>
The script:
<script>
export default {
props: {
hotels: Array,
},
data() {
return {
facilities: [
{
iconClass: "fas fa-door-open fa-fw fa-lg icon-class ml-2 mr-2",
name: 'Number of rooms:',
function: this.numberOfRooms,
}
],
}
},
computed: {
numberOfRooms(){
if(this.hotels[0].hotel.numberRooms > 0) {
return this.hotels[0].hotel.numberRooms
}
},
}
}
</script>
答案1
得分: 1
一个简单的解决方案是将facilities
定义为计算属性:
export default {
props: {
hotels: Array,
},
computed: {
numberOfRooms(){
if(this.hotels[0].hotel.numberRooms > 0) {
return this.hotels[0].hotel.numberRooms
}
},
facilities(){
return [
{
iconClass: "fas fa-door-open fa-fw fa-lg icon-class ml-2 mr-2",
name: 'Number of rooms:',
function: this.numberOfRooms,
}
],
}
}
}
英文:
A simple solution is to define facilities
as a computed property :
export default {
props: {
hotels: Array,
},
computed: {
numberOfRooms(){
if(this.hotels[0].hotel.numberRooms > 0) {
return this.hotels[0].hotel.numberRooms
}
},
facilities(){
return [
{
iconClass: "fas fa-door-open fa-fw fa-lg icon-class ml-2 mr-2",
name: 'Number of rooms:',
function: this.numberOfRooms,
}
],
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论