[英]How to use the props in vue component?
I try to use a prop in a computed value and i keep getting the error:我尝试在计算值中使用道具,但我不断收到错误消息:
[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pages/space-details.vue at src/App.vue
[Vue 警告]:渲染错误:“类型错误:无法读取未定义的属性‘长度’”在 ---> 中找到,位于 src/cmps/space-details/space-imgs.vue 位于 src/pages/space-details。 vue 在 src/App.vue
Maybe i'm using the prop wrong?也许我用错了道具? the component:
组件:
<template>
<div v-if="imgUrls.length" class="space-imgs" :class="pics">
<img :src="img" v-for="(img, idx) in imgUrls.slice(0, 5)" :key="idx" />
</div>
</template>
<script>
export default {
props: { imgUrls: Array },
computed: {
pics() {
return `pics-${this.imgUrls.length}`;
},
},
};
</script>
and this is how i pass the prop:这就是我传递道具的方式:
<space-imgs :imgUrls="space.imgUrls" />
Thanks谢谢
Your template will be first rendered before the prop is passed, making imgUrls
undefined.您的模板将在传递 prop 之前首先呈现,从而使
imgUrls
未定义。 So just do this: v-if="imgUrls"
.所以就这样做:
v-if="imgUrls"
。
Pass the prop like below.像下面一样传递道具。 This will work.
这将起作用。
<space-imgs :img-urls="space.imgUrls" />
For avoiding wrong prop data in component.用于避免组件中错误的道具数据。 initialize prop with default value.
用默认值初始化 prop。
props: {
imgUrls: {
type: Array,
default: [],
required: true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.