vue ref

‌‌Vue中的‌ref主要用于创建响应式变量和直接访问DOM元素/组件实例‌,是Vue响应式系统的核心API之一。

Vue ref的核心功能

‌1、响应式数据管理‌:

  • 通过ref()函数将基本类型或复杂类型数据转化为响应式对象,数据变更自动触发视图更新。‌‌
  • 组合式API中必须通过.value属性操作数据(如const count = ref(0); count.value++)。‌‌

2‌、DOM与组件操作‌:

  • 在模板中通过ref="xxx"标记元素,通过this.$refs.xxx直接获取DOM节点(Vue 2)或组件实例。‌‌
  • ‌Vue 3中使用<script setup>时,需通过const el = ref(null)声明引用

使用场景示例

  • ‌‌表单验证‌:通过ref获取输入框DOM实时校验内容。
  • ‌‌动画控制‌:直接操作DOM元素的样式属性实现复杂动画。
  • ‌‌组件通信‌:父组件通过ref调用子组件暴露的方法(如this.$refs.child.validateForm())。‌‌

用在普通DOM标签上:

复制代码
<template>

  <h1 ref="title1"> 中国</h1>
  <h2 ref="title2"> 河南</h2>
  <h3 ref="title3"> 洛阳</h3>
  <input type="text" ref="inpt"> <br><br>
  <button @click="showLog">点我打印内容</button>
</template>

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

let title1 = ref()
let title2 = ref()
let title3 = ref()

function showLog() {
  // 通过id获取元素
  const t1 = document.getElementById('title1')
  if (t1) {
    t1.innerText = "新的文本";
    // 打印内容
    console.log((t1 as HTMLElement).innerText)
    console.log((<HTMLElement>t1).innerText)
    console.log(t1?.innerText)
  } else {
    console.log("元素未找到");
  }

  // 通过ref获取元素
  console.log(title1.value)
  console.log(title2.value)
  console.log(title3.value)
}
</script>

用在组件标签上:

复制代码
<!-- 父组件App.vue -->
<template>
  <Person ref="ren"/>
  <button @click="test">测试</button>
</template>

<script lang="ts" setup name="App">
  import Person from './components/Person.vue'
  import {ref} from 'vue'

  let ren = ref()

  function test(){
    console.log(ren.value.name)
    console.log(ren.value.age)
  }
</script>


<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">
  import {ref,defineExpose} from 'vue'
	// 数据
  let name = ref('张三')
  let age = ref(18)
  /****************************/
  /****************************/
  // 使用defineExpose将组件中的数据交给外部
  defineExpose({name,age})
</script>
相关推荐
再学一点就睡1 天前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
C_心欲无痕1 天前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕1 天前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong1 天前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
柳杉1 天前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_462446231 天前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化
CheungChunChiu1 天前
Linux 内核动态打印机制详解
android·linux·服务器·前端·ubuntu
Irene19911 天前
Vue 官方推荐:kebab-case(短横线命名法)
javascript·vue.js
GIS之路1 天前
GDAL 创建矢量图层的两种方式
前端
2501_948195341 天前
RN for OpenHarmony英雄联盟助手App实战:符文配置实现
javascript·react native·react.js