Skip to content

获取模板引用

可以通过标签的 ref 属性拿到当前组件的虚拟 DOM 引用,如果此时组件尚未挂载,则返回 null,因此在侦听这些值的时候要注意判断空值。

  • 只有在组件挂载后才能访问模板引用
html
<script setup>
import { ref, onMounted } from 'vue'

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

onMounted(() => {
  input.value.focus()
})
</script>

<template>
  <input ref="input" />
</template>

v-for 的模板引用

v-for 渲染的每一个 DOM 的引用会被添加到标签 ref 属性指定的 ref 响应式对象中

html
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([1, 2, 3])
const itemRefs = ref([])
</script>
<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

组件标签的 ref

html
<template>
  <Child ref="child" />
</template>

拿到子组件的实例后,可以直接操作子组件的一些暴露的东西(setup 默认不暴露)。 比如操作一个子组件的 x 变量:

html
<template>
    <child ref="childRef"></child>
</template>

<script setup lang="ts" name="test">
import { ref, onMounted, defineComponent } from 'vue'
import child from './child.vue'
let childRef = ref<InstanceType<typeof child> | null>(null)

onMounted(() => {
    if (childRef.value) {
        console.log(childRef.value.x)
    }
})