Vue3响应式对象API超全实例详解,有哪些应用场景和技巧?

2026-03-31 15:301阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计400个文字,预计阅读时间需要2分钟。

Vue3响应式对象API超全实例详解,有哪些应用场景和技巧?

目录- ref (+递归监听+)- isRef (+判断+)- toRef (+结构+)- toRaw (+解除代理+)- unref (+拷贝+)- shallowRef (+非递归监听+)- shallowReactive (+非递归监听+)

目录
  • Ⅰ. ref、reactive ( 递归监听 )
  • Ⅱ. isRef、isReactive ( 判断 )
  • Ⅲ. toRef 和 toRefs ( 解构 )
  • Ⅳ. toRaw 、 markRaw ( 解除代理)
  • Ⅴ. unref ( 拷贝 )
  • Ⅵ. shallowRef 、shallowReactive( 非递归监听 )
  • Ⅶ. triggerRef (强制更新)
  • 总结

Ⅰ. ref、reactive ( 递归监听 )

import {ref,reactive} from 'vue'; setup() { const num = ref(123); num.value = 456; const obj = reactive({num:123}); obj.value = 456; }

  • ref 对象 在 html 模板中会 自动添加 value ( ref 对象中__v_isRef:true 进行判断的 )
  • ref 对象 => reactive( { value:0 } ) 底层自动转换为 reactive
  • 最终 基本数据 类型采用 => (Object.defineProperty) ,引用数据 类型采用 => ( proxy 代理 )

Vue3响应式对象API超全实例详解,有哪些应用场景和技巧?

Ⅱ. isRef、isReactive ( 判断 )

import {isRef,isReactive} from 'vue'; setup() { const num = ref(123) console.log(isRef(num)) // => true }

  • 用于判断是否是 Ref 和 Reactive 创建的响应对象
  • 使用场景较少

Ⅲ. toRef 和 toRefs ( 解构 )

toRef (一个属性)

import { toRef , reactive } from 'vue'; setup() { const obj = reactive({ width:10, height:20 }) const width = toRef(obj,'width') return { width } }

将一个响应对象的属性,当作 响应对象 单独拿出来 。

toRefs ( 所有 )

import { toRefs , reactive } from 'vue'; setup() { const obj = reactive({ width:10, height:20 }) const { width, height }= toRefs(obj) return { width, height } }

将多个或所有属性,拿出来 且还是响应对象,一般在返回的时候一次性全部导出

本文共计400个文字,预计阅读时间需要2分钟。

Vue3响应式对象API超全实例详解,有哪些应用场景和技巧?

目录- ref (+递归监听+)- isRef (+判断+)- toRef (+结构+)- toRaw (+解除代理+)- unref (+拷贝+)- shallowRef (+非递归监听+)- shallowReactive (+非递归监听+)

目录
  • Ⅰ. ref、reactive ( 递归监听 )
  • Ⅱ. isRef、isReactive ( 判断 )
  • Ⅲ. toRef 和 toRefs ( 解构 )
  • Ⅳ. toRaw 、 markRaw ( 解除代理)
  • Ⅴ. unref ( 拷贝 )
  • Ⅵ. shallowRef 、shallowReactive( 非递归监听 )
  • Ⅶ. triggerRef (强制更新)
  • 总结

Ⅰ. ref、reactive ( 递归监听 )

import {ref,reactive} from 'vue'; setup() { const num = ref(123); num.value = 456; const obj = reactive({num:123}); obj.value = 456; }

  • ref 对象 在 html 模板中会 自动添加 value ( ref 对象中__v_isRef:true 进行判断的 )
  • ref 对象 => reactive( { value:0 } ) 底层自动转换为 reactive
  • 最终 基本数据 类型采用 => (Object.defineProperty) ,引用数据 类型采用 => ( proxy 代理 )

Vue3响应式对象API超全实例详解,有哪些应用场景和技巧?

Ⅱ. isRef、isReactive ( 判断 )

import {isRef,isReactive} from 'vue'; setup() { const num = ref(123) console.log(isRef(num)) // => true }

  • 用于判断是否是 Ref 和 Reactive 创建的响应对象
  • 使用场景较少

Ⅲ. toRef 和 toRefs ( 解构 )

toRef (一个属性)

import { toRef , reactive } from 'vue'; setup() { const obj = reactive({ width:10, height:20 }) const width = toRef(obj,'width') return { width } }

将一个响应对象的属性,当作 响应对象 单独拿出来 。

toRefs ( 所有 )

import { toRefs , reactive } from 'vue'; setup() { const obj = reactive({ width:10, height:20 }) const { width, height }= toRefs(obj) return { width, height } }

将多个或所有属性,拿出来 且还是响应对象,一般在返回的时候一次性全部导出