admin管理员组文章数量:1123587
<template>
<div ref="items" v-for="(item, index) in data" :key="index">{{ item }}</div>
</template>
<script setup>
import { defineProps, ref, useTemplateRef, onMounted } from 'vue'
const props = defineProps({ data: Array })
const items = useTemplateRef('items')
onMounted(() => {
console.log(items.value)
})
</script>
It's did as described here, but using data props
instead of const list = ref([...])
The data props
comes from parent component and looks like [{...}, {...}, {...}]
The problem: items.value
is null
in case of loop through the data props
.
Vue 3.5.13.
How to deal with it?
<template>
<div ref="items" v-for="(item, index) in data" :key="index">{{ item }}</div>
</template>
<script setup>
import { defineProps, ref, useTemplateRef, onMounted } from 'vue'
const props = defineProps({ data: Array })
const items = useTemplateRef('items')
onMounted(() => {
console.log(items.value)
})
</script>
It's did as described here, but using data props
instead of const list = ref([...])
The data props
comes from parent component and looks like [{...}, {...}, {...}]
The problem: items.value
is null
in case of loop through the data props
.
Vue 3.5.13.
How to deal with it?
Share Improve this question asked 22 hours ago MapUserMapUser 4031 gold badge4 silver badges15 bronze badges 3 |1 Answer
Reset to default 0You're seeing this error because your component expects an array in props.data
but at some point it its lifecycle it receives a falsey value, namely null
.
There are several ways to avoid this.
- You could skip rendering the component while the prop value is
null
, placing av-if
on it:
<MyComp v-if="myData?.length" :data="myData" />
,in the parent component.
- Or you could provide a default value to
props.data
:
const props = withDefaults(defineProps({ data: Array }), { data: [] })
This solution has the advantage of allowing you to deal with no data case inside the child component, so the parent doesn't need to worry about it:
<template>
<div ref="items" v-for="(item, index) in data" :key="index">{{ item }}</div>
<div v-if="!data.length">
No data here...
¯\_(ツ)_/¯
</div>
</template>
本文标签: vuejs3Template ref for loop through propsStack Overflow
版权声明:本文标题:vuejs3 - Template ref for loop through props - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736583048a1944974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
withDefaults(defineProps({ data: Array }), { data: [] })
should fix it. It setsprops.data
to empty array when it's falsey. Or you could place av-if="data?.length"
on the component, in the parent's template. – tao Commented 17 hours agov-if
solves the problem. – MapUser Commented 16 hours ago