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
  • withDefaults(defineProps({ data: Array }), { data: [] }) should fix it. It sets props.data to empty array when it's falsey. Or you could place a v-if="data?.length" on the component, in the parent's template. – tao Commented 17 hours ago
  • @Alexander Nenashev The data is loaded async indeed. Advice about v-if solves the problem. – MapUser Commented 16 hours ago
  • @tao Could you answer the question to mark one as resolved? – MapUser Commented 16 hours ago
Add a comment  | 

1 Answer 1

Reset to default 0

You'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.

  1. You could skip rendering the component while the prop value is null, placing a v-if on it:
  <MyComp v-if="myData?.length" :data="myData" />

,in the parent component.

  1. 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