vue.js - 无法获取计算属性(数组)
问题描述
试图将 ' displayImages
' 数组作为计算属性。使用默认的“ selected
”属性 = 0
。this.selected 在 mouseover 和 click 事件上相应改变。
当试图得到计算的 ' displayImages
' 它说:
"this.variations[this.selected] is undefined."
我正在使用 api 来获取我的产品数据和图像。
<template>
<div id="product-page">
<v-card width="100%" class="product-card">
<div class="image-carousel">
<v-carousel height="100%" continuos hide-delimiters>
<v-carousel-item
v-for="(image, i) in displayImages"
:key="i"
:src="image"
>
</v-carousel-item>
</v-carousel>
</div>
<div class="details">
<h2>{{ this.title }}<br />Price: ${{ this.price }}</h2>
<p>{{ this.details }}</p>
<ul style="list-style: none; padding: 0">
<li
style="border: 1px solid red; width: auto"
v-for="(color, index) in variations"
:key="index"
@mouseover="updateProduct(index)"
@click="updateProduct(index)"
>
{{ color.color }}
</li>
</ul>
<div class="buttons">
<v-btn outlined rounded
>ADD TO CART<v-icon right>mdi-cart-plus</v-icon></v-btn
>
<router-link to="/shop">
<v-btn text outlined rounded> BACK TO SHOP</v-btn>
</router-link>
</div>
</div>
</v-card>
</div>
</template>
<script>
export default {
name: "Product",
props: ["APIurl"],
data: () => ({
title: "",
details: "",
price: "",
variations: [],
selected: 0,
}),
created() {
fetch(this.APIurl + "/products/" + this.$route.params.id)
.then((response) => response.json())
.then((data) => {
//console.log(data);
this.title = data.title;
this.details = data.details.toLowerCase();
this.price = data.price;
data.variations.forEach((element) => {
let imagesArray = element.photos.map(
(image) => this.APIurl + image.url
);
this.variations.push({
color: element.title,
images: imagesArray,
qty: element.qty,
productId: element.productId,
});
});
});
},
computed: {
displayImages() {
return this.variations[this.selected].images;
},
},
methods: {
updateProduct: function (index) {
this.selected = index;
console.log(index);
}
},
};
</script>
解决方案
为了避免这种错误,您必须使用安全导航属性。
请记住,它仅在应用程序加载时很有用。
尝试这样的事情:
<script>
export default {
name: 'Product',
computed: {
displayImages() {
if (this.variations[this.selected]) {
return this.variations[this.selected].images;
}
return [];
},
},
};
</script>
推荐阅读
- c - 包含字符串和浮点数的函数,我从 main 调用它。但是错误
- kubernetes - 如何将 kubernetes YAML 文件转换为 DC/OS JSON
- python - 当您将两个列表“和”在一起时会发生什么?
- kendo-react-ui - kendo-react-layout 编译失败
- java - Sqlite 数据库上下文 android
- java - 使用 @KafkaListener 注释的方法不会传播遇到的异常。由于这个原因,无法调用我的重试配置
- node.js - 导入 var firebaseui = require('firebaseui'); 错误窗口未定义
- c# - 如何在 C# 中向服务器发送文件和字符串?
- matlab - 如何在 MATLAB 中使用三次方程求解器求解/优化 9 个非线性方程?
- proxy - 在单个域上部署多个存储库(通过 Netlify 中的代理)