Changes in using ref on components in Vue3, especially ref under the v-for syntax!

foreword

Compared with Vue3, Vue3 has made many optimizations, and the syntax has also changed. Among them, the ref writing on the v-for loop generation component changes greatly, and it is easy to step on the pit, so it is hereby recorded.

ref definition

ref Is a special attribute, similar to  v-for in  key . It allows us to get a direct reference to a particular DOM element or subcomponent instance after it has been mounted.

easy to use

In order to get the Dom through the composition API, we need to declare a ref with the same name

<template>
  <h4 ref="test">我是测试ref的元素</h4>
</template>

<script setup lang="ts">
  import { ref } from 'vue'

  // 声明一个 ref 来存放该元素的引用
  // 必须和模板里的 ref 同名
  const test = ref(null)
</script>

Note that template references are only accessible after the component is mounted . If you wanted to access "test" on an expression in the template, it would be on the first render  null. This is because the element does not exist before the initial render!

Similarly, if you need to listen to changes in a template reference ref, make sure to take into account its value  null :

watchEffect(() => {
  if (test.value) {
    ...
  } else {
    // 此时还未挂载,或此元素已经被卸载(例如通过 v-if 控制)
  }
})

Use in v-for

When  v-for using a template reference in , the value contained in the corresponding ref is an array that will contain all elements corresponding to the entire list after the element is mounted:

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

// v-for 循环列表
const list = ref(['a', 'b', 'c'])

// 跟简单使用不同,不是null,而是一个空数组
const itemRefs = ref([])

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

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

 

Guess you like

Origin blog.csdn.net/weixin_42373175/article/details/130399692