图标
文章摘要
LANZLZ.CN-GPT

|

一、ref()的作用

ref() 接受一个内部值,返回一个ref 对象,这个对象是响应式的、可更改的,且只有一个指向其内部值的属性 .value。

ref() 将传入参数的值包装为一个带 .value 属性的 ref 对象。

二、处理响应式数据

1、ref 对象是可更改的,即可以为 .value 赋予新的值

举例:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
const a = ref(1); // 为 a.value 赋予新的值 a.value = 2; console.log("a--->", a); console.log("a.value--->", a.value);

查看打印结果:

2、ref 对象是响应式的,即所有对 .value 的操作都将被追踪,并且写操作会触发与之相关的副作用。

ref()方法允许创建可以使用任何值类型的响应式 ref。ref 的 .value 属性也是响应式的。

当ref的值为对象类型时,会用 reactive() 自动转换它的 .value。

举例:一个包含对象类型值的 ref 可以响应式地替换整个对象

  • 01
  • 02
  • 03
  • 04
  • 05
const b = ref({ name: 'vue3' }); // 响应式替换b.value = { name: 'vite' }; console.log("b--->", b); console.log("b.value--->", b.value);

查看打印结果:

ref 被传递给函数或是从一般对象上被解构时,不会丢失响应性:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
const obj = { foo: ref(0), bar: ref(1) } // 该函数接收一个 ref // 需要通过 .value 取值 // 但它会保持响应性 callSomeFunction(obj.foo); // 仍然是响应式的 const { foo, bar } = obj;

总结:ref() 让我们能创造一种对任意值的 “引用”,并能够在不丢失响应性的前提下传递这些引用。这个功能很重要,因为它经常用于将逻辑提取到组合函数中。

3、ref 在模板中的解包

当 ref 在模板中作为顶层属性被访问时,它们会被自动“解包”,所以不需要使用 .value。

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
<script setup> import { ref } from 'vue'; const a = ref(1); </script> <template> <!-- 无需 .value --> <div>a:{{ a }}</div> </template>

请注意,仅当 ref 是模板渲染上下文的顶层属性时才适用自动“解包”。

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
<script setup> import { ref } from 'vue'; const obj = { count: ref(1) } </script> <template> <div>{{ obj.count + 1 }}</div> </template>

渲染的结果是 [object Object] 1,因为 object.count 是一个 ref 对象

可以通过将 count 改成顶层属性来解决这个问题:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
<script setup> import { ref } from 'vue'; const obj = { count: ref(1) } // 将 count 改成顶层属性 const { count } = obj; </script> <template> <div>{{ count + 1 }}</div> </template>

渲染结果是 2

如果一个 ref 是文本插值计算的最终值,它也将被解包

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
<script setup> import { ref } from 'vue'; const obj = { count: ref(1) } const { count } = obj; </script> <template> <div>{{ count + 1 }}</div> <div class="count">{{ obj.count }}</div> </template>

{{ obj.count }} 的渲染结果为 1,这只是文本插值的一个方便功能,相当于 {{ object.foo.value }}

4、ref 在响应式对象中的解包

当一个 ref 被嵌套在一个响应式对象中,作为属性被访问或更改时,它会自动解包,因此会表现得和一般的属性一样:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
import { ref, reactive } from 'vue'; const a = ref(0); const obj = reactive({ a }) console.log("obj.a--->", obj.a); obj.a = 2; console.log("a.value--->", a.value);

查看打印结果:

如果将一个新的 ref 赋值给一个关联了已有 ref 的属性,那么它会替换掉旧的 ref:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
import { ref, reactive } from 'vue'; const a = ref(0); const other = ref(1); const obj = reactive({ a }) // 将一个新的 ref 赋值给一个关联了已有 ref 的属性 obj.a = other; console.log("obj.a--->", obj.a); // 原始 ref 现在已经和 obj.a 失去联系 console.log("a.value--->", a.value);

查看打印结果:

只有当嵌套在一个深层响应式对象内时,才会发生 ref 解包。当其作为浅层响应式对象的属性被访问时不会解包。

5、ref在数组和集合类型的解包

跟响应式对象不同,当 ref 作为响应式数组或像 Map 这种原生集合类型的元素被访问时,不会进行解包。

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
import { ref, reactive } from 'vue'; const books = reactive([ref('Vue 3 Guide')]); // 这里需要 .value console.log(books[0].value); const map = reactive(new Map([['count', ref(0)]])); // 这里需要 .value console.log(map.get('count').value);

6、ts为 ref() 标注类型

ref 会根据初始化时的值推导其类型:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
import { ref } from 'vue' // 推导出的类型:Ref<number> const year = ref(2020) // => TS Error: Type 'string' is not assignable to type 'number'. year.value = '2020'

有时我们可能想为 ref 内的值指定一个更复杂的类型,可以通过使用 Ref 这个类型

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
import { ref } from 'vue' import type { Ref } from 'vue' const year: Ref<string | number> = ref('2020') year.value = 2020 // 成功!

或者,在调用 ref() 时传入一个泛型参数,来覆盖默认的推导行为:

  • 01
  • 02
  • 03
  • 04
// 得到的类型:Ref<string | number> const year = ref<string | number>('2020') year.value = 2020 // 成功!

如果你指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型:

  • 01
  • 02
// 推导得到的类型:Ref<number | undefined> const n = ref<number>()

三、用于访问组件中的 DOM 元素

3.1 访问 DOM 元素

通过 ref 可以访问到在组件中定义的 DOM 元素,例如:input、div、img 等。可以使用 $refs 属性访问到这些元素。

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
<template> <div> <input ref="myInput" type="text"> <button @click="focusInput">Focus Input</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const myInput = ref(null) function focusInput() { myInput.value.focus() } return { myInput, focusInput } } } </script>

3.2 访问组件实例

可以使用 ref 访问到组件的实例,以便在父组件中直接调用子组件中暴露的方法或访问子组件中暴露的数据。

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
<template> <div> <Child ref="childComponent" /> <button @click="callChildMethod">Call Child Method</button> </div> </template> <script> import Child from './Child.vue' export default { components: { Child }, setup() { const childComponent = ref(null) function callChildMethod() { childComponent.value.myMethod() } return { childComponent, callChildMethod } } } </script>

3.3 存储任何需要在组件中进行状态管理的值

除了用于处理响应式数据,ref 还可以用于存储任何需要在组件中进行状态管理的值,例如:定时器 ID、请求状态等等。

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
<template> <div> <p v-if="isLoading">Loading...</p> <button @click="fetchData">Fetch Data</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const isLoading = ref(false) const timerId = ref(null) function fetchData() { isLoading.value = true timerId.value = setTimeout(() => { isLoading.value = false clearTimeout(timerId.value) }, 3000) } return { isLoading, fetchData } } } </script>

结语

这些都是 ref 函数在 Vue 3 中的一些用法,除了处理响应式数据之外,它还可以访问 DOM 元素、组件实例以及存储任何需要在组件中进行状态管理的值,使得 Vue 3 变得更加灵活和方便。