当前位置:首页 > VUE

vue ref实现

2026-02-10 09:52:13VUE

Vue 中 ref 的实现

在 Vue 中,ref 是一个用于创建响应式引用的 API。它可以用于基本类型、对象或组件实例,并确保其值是响应式的。

基本用法

import { ref } from 'vue'

const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

实现原理

ref 的核心是通过一个对象包装原始值,利用 Vue 的响应式系统跟踪变化。当访问或修改 .value 时,会触发依赖收集和更新。

vue ref实现

function ref(value) {
  return {
    get value() {
      track(this, 'value') // 依赖收集
      return value
    },
    set value(newVal) {
      value = newVal
      trigger(this, 'value') // 触发更新
    }
  }
}

在模板中使用

在模板中,ref 会自动解包,无需使用 .value

<template>
  <div>{{ count }}</div>
  <button @click="count++">Increment</button>
</template>

<script setup>
const count = ref(0)
</script>

与 reactive 的区别

ref 适用于基本类型或需要直接替换整个对象的情况,而 reactive 适用于对象或数组。ref 通过 .value 访问,reactive 直接访问属性。

vue ref实现

const objRef = ref({ foo: 1 })
const objReactive = reactive({ foo: 1 })

objRef.value.foo = 2
objReactive.foo = 2

在组件上使用

ref 可以用于获取组件实例:

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

<script setup>
import { ref } from 'vue'
const child = ref(null)

onMounted(() => {
  console.log(child.value) // 组件实例
})
</script>

类型定义 (TypeScript)

在 TypeScript 中,ref 可以明确指定类型:

const count = ref<number>(0)
const user = ref<{ name: string }>({ name: 'Alice' })

注意事项

  • 在组合式 API 中始终通过 .value 访问 ref 的值
  • 在模板中会自动解包,无需 .value
  • 避免在 reactive 对象中直接替换整个 ref,应替换 .value

标签: vueref
分享给朋友:

相关文章

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现通知

vue实现通知

Vue 实现通知功能的方法 使用 Vue 实现通知功能可以通过多种方式实现,以下是一些常见的方法: 使用 Vue 的全局事件总线 在 Vue 中可以通过事件总线实现通知功能。创建一个全局事件总线,然…

vue实现模块

vue实现模块

Vue 实现模块化的方法 Vue 支持多种模块化开发方式,可以根据项目需求选择适合的方案。 使用单文件组件(SFC) 单文件组件是 Vue 最常用的模块化方式,将模板、脚本和样式封装在一个 .vue…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Router 实现…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…