Subscribe on changes!

Refs inside v-for does not work when ref is used in setup

avatar
Feb 18th 2022

Version

3.2.31

Reproduction link

stackblitz.com

Steps to reproduce

<template>
  <div id="app">
    <button ref="btn" @click="show">test</button>
    <div ref="itemRefs" v-for="item in list" :key="item">{{ item }}</div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
export default {
  name: "App",
  setup() {
    const list = ref(["a", "b", "c"]);
    const itemRefs = ref([]);
    const btn = ref();
    onMounted(() => {
      alert(itemRefs.value[0]);
      alert(btn.value.textContent);
    });
    return { list, itemRefs, btn };
  },
  methods: {
    show() {
      alert(this.$refs.itemRefs[0].textContent);
    },
  },
};
</script>

What is expected?

The contents of alter should be " a, b,c"

What is actually happening?

TypeError: Cannot read properties of undefined

avatar
Feb 18th 2022

#5447