Skip to content

模板引用

有时候我们需要拿到DOM元素来进行一些错做,这是可以使用ref attribute

html
<input ref="input" />

ref是一个特殊的attribute,允许我们在一个特定的DOM元素或子组件实例被挂载后获得对它的直接引用.

访问模板引用

在组合式API中,我们可以通过辅助函数useTemplateRef()(3.5+)来获得DOM元素

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

// 第一个参数必须与模板中的 ref 值匹配
const input = useTemplateRef('my-input')

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

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

而在 3.5 版本之之前,需要生命一个与模板里refattribute匹配的引用

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

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

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

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

如果不适用<script setup> 需要确保从setup()返回ref:

javascript
export default {
  setup() {
    const input = ref(null)
    // ...
    return {
      input,
    }
  },
}

注意: 只有在在组件挂载后才能访问模板引用,否则获取到的会是null,所以如果想要侦听一个模板引用的变化 确保考虑到了null的情况:

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

组件上的ref

模板应用用在组件上获取的值是组件的实例:

html
<script setup>
  import { useTemplateRef, onMounted } from 'vue'
  import Child from './Child.vue'

  const childRef = useTemplateRef('child')

  onMounted(() => {
    // childRef.value 将持有 <Child /> 的实例
  })
</script>

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

3.5 前的用法:

html
<script setup>
  import { ref, onMounted } from 'vue'
  import Child from './Child.vue'

  const child = ref(null)

  onMounted(() => {
    // child.value 是 <Child /> 组件的实例
  })
</script>

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

如果组件使用的是选项式API,或者没有使用<script setup>,被应用的组件实例和该子组件的this一致.这意味着父组件对子组件的每一个属性个方法都有完全的访问权限 这使得父组件和子组件之前创建紧密耦合的实现细节变得很容易,也因为如此,应该只在绝对需要的收才使用组件应用.大多数情况下应该首先使用标准的propsemit来实现父子 组件的交互

使用了<script setup>的组件是默认私有的 --- 一个父组件无法访问到一个使用了<script setup>的子组件中的任何东西,除非子组件通过defineExpose宏显示暴露:

html
<script setup>
  import { ref } from 'vue'

  const a = 1
  const b = ref(2)

  // 像 defineExpose 这样的编译器宏不需要导入
  defineExpose({
    a,
    b,
  })
</script>

当父组件通过模板引用获取到该组件的实例时,得到的室内类型为{ a: number, b: number }
需要注意,defineExpose必须在任何await操作之前进行调用,否则await操作之后暴露的属性和方法都将无法访问

v-for中的模板引用

v-for中使用时,获取的值是一个数组,它将在元素被挂载后包含整个列表的所有元素

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

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

  const itemRefs = useTemplateRef('items')

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

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

3.5 之前的用法:
3.5版本之前需要声明一个与模板引用attribute同名的ref,该ref的值需要是一个数组

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

注意: ref数组并不保证与源数组的数序相同

函数模板引用

除了使用字符串值作为名字,模板引用还可以绑定为一个函数,会在每次组件更行事都被调用,该函数还会收到元素引用作为第一个参数

html
<input :ref="(el) => { /* 将 el 赋值给一个数据属性或 ref 变量 */ }" />

需要注意: 只有动态绑定(:ref)才能传入函数,当绑定的元素被卸载时,函数也会被调用一次,此时el参数的值会使null,除了内联函数也可以绑定一个组件中的方法