vuejs3v-forvue-props

Template ref for loop through props


<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?


Solution

  • 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>