Skip to content
On this page

Ref 的小技巧

Authors

vue.js 组件中重新分配值可能会导致使用模板 ref 的最简单形式时出现问题:

vue
<template>
  <div>
    <h1 ref="heading">这是标题</h1>
  </div>
</template>

在这种情况下,我们根本不能使用响应式对象:

vue
<script setup lang="ts">
import { reactive,watchEffect } from 'vue'

const heading = reactive(null)

watchEffect(()=>{
  console.log(heading) // "null"
})
</script>

当组件首次实例化时,这将记录 null ,因为 heading 还没有值。

但是,当组件挂载并创建我们的 h1 时,它不会触发。

heading 对象变成了一个新对象,我们的 watcher 失去了它的跟踪。

对先前的响应式对象的引用被覆盖了。

我们需要在这里使用 ref:

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

const heading = ref(null)

watchEffect(()=>{
  console.log(heading.value) // "null"
})
</script>

这次,当组件挂载时,它将记录该元素。

这是因为只有 ref 可以以这种方式重新分配。

在这种情况下,使用响应式是可能的,但需要使用函数 ref 的一些额外语法:

然后,我们的脚本将如下所示,使用我们的响应式对象上的 el 属性:

vue
<template>
  <div>
    <h1 :ref="(el)=>{ heading.value = el }">这是标题</h1>
  </div>
</template>

有关更多信息,请参阅文档:https://cn.vuejs.org/guide/essentials/template-refs.html

has loaded