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>
相关推荐
Geoffwo几秒前
robotjs0.6.0鼠标中轴滚动失效修复方案
前端·javascript
彭亚川Allen11 分钟前
从零手搓 RAG 之文档解析技术
前端·后端·架构
oicola34 分钟前
Ant Design v5 vs Tailwind CSS:组件库与样式框架的终极对决
前端·css
溪语流沙39 分钟前
【Web全栈进阶】Vue Router + Pinia:SPA路由与全局状态
前端·javascript·vue.js
ManageEngineITSM1 小时前
工单优先级怎么定?影响×紧急度矩阵的设计与落地方法
java·大数据·运维·前端·数据库·变更管理
智商网输送线配件1 小时前
电子制造零散耗材补货实战:小批量混批采购平台怎么选才不停机?
大数据·服务器·前端·数据库·自动化
梦帮科技1 小时前
Web 漏洞攻防深度:WAF 规则逃逸技术(畸形分块传输、双重编码)与对抗加固
linux·前端·网络安全·ssl·web
兰亭妙微UI设计公司1 小时前
兰亭妙微软件界面设计公司的解锁按钮设计10大密码
开发语言·前端·javascript
迪幻1 小时前
封装自己的 npm 依赖并存储到个人 GitHub
前端·npm·github
u0111026752 小时前
WebP 转成 PNG 后为什么更大?图片格式转换不等于压缩
前端·javascript·vue.js