Home  >  Q&A  >  body text

How do template references work within constants?

About the problem of template reference in vue

I was looking at the vue documentation about "refs" and in the section where it explains refs inside v-for it gives the following example:

<script setup>
import { ref, onMounted } from 'vue'

const list = ref([
  /* ... */
])

const itemRefs = ref([])

onMounted(() => console.log(itemRefs.value))
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

I can understand its purpose

const itemRefs = ref([])

But I don't understand why ref is also applied to

const list = ref([
   /* ... */
])

In the sandbox, it is possible to remove the reference from the "list constant" without harming the function, so what is the real application inside this constant?

<script setup>
import { ref, onMounted } from 'vue'

// const with ref
const list = ref([1, 2, 3])

const itemRefs = ref([])

onMounted(() => {
  alert(itemRefs.value.map(i => i.textContent))
})
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>
<script setup>
import { ref, onMounted } from 'vue'

// const without ref
const list = ([1, 2, 3])

const itemRefs = ref([])

onMounted(() => {
  alert(itemRefs.value.map(i => i.textContent))
})
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

P粉777458787P粉777458787406 days ago511

reply all(1)I'll reply

  • P粉691958181

    P粉6919581812023-09-10 14:13:38

    Use ref to convert list into a reactive variable. Whenever a new item is added or otherwise changed, other functions or template parts that monitor it will be updated. In the example without ref , when you append a new item to the list, it is not automatically rendered in the template.

    I can understand your confusion, I guess you may be from vue2 world. I highly recommend reading the vue3 documentation on reactivity.

    reply
    0
  • Cancelreply