我正在使用 for 循环来显示页面上的项目列表。如您所见,每个对象都在我的数组中声明。
const animals = [
{
name: "monkey",
food: "fruit",
img: "images/fruit.jpg",
},
{
name: "horse",
food: "hay",
img: "images/hay.jpg",
},
{
name: "sealion",
food: "fish",
img: "images/fish.jpg",
}
];
new Vue ({
el: '#app',
data: {
zoo: animals
}
});
下面的代码将在列表页面上打印动物及其喜欢的食物的列表。
<ul>
<li v-for="(item, index) in zoo">
<p>{{index }} {{ item.name }}</p>
<p>{{index }} {{ item.food }}</p>
</li>
</ul>
但是,我还需要在网站的其他地方使用此数组中存储的信息。但是,这次不是循环。
对于单独的详细信息页面,我只需要第三只动物的信息(索引位置 2)
<h2>My favorite animal is a {{ item[2].name }} and it eats {{ item[2].food }} </h2>
有办法做到这一点吗?
最佳答案
您的代码可以正常工作,但为了更具防御性,最好创建一个方法(或过滤器)来从数组中获取特定元素,例如方法示例:
methods: {
getAnimalByIndex({ animals = [], index = 0 }) {
return animals[index] || {}
}
}
...然后在模板中使用,如下所示:
<h2>My favorite animal is a {{ getAnimalByIndex({ animals, index: 2 }).name }} and it eats {{ getAnimalByIndex({ animals, index: 2 }).food }} </h2>
感谢上述内容,您可以提供后备值,或者确保即使动物未定义也可以;)
此外,如果您想始终获得第三种动物,那么使用计算值也许是个好主意,如下所示:
computed: {
thirdAnimal() {
return this.animals[2] || {}
}
}
...并在模板中使用计算值:
<h2>My favorite animal is a {{ thirdAnimal.name }} and it eats {{ thirdAnimal.food }} </h2>
关于javascript - 如何在 VueJs 中显示数组中的单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54430398/