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 小时前
在 Vue Router 4 中,如何设置base参数
前端·javascript·vue.js
Lovely_Ruby2 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·后端
kong@react2 小时前
react+ts项目,富文本开发(wangEditor)
前端·react.js·前端框架
重铸码农荣光2 小时前
AI First + Mobile First:用大模型重构下一代应用开发范式
前端·架构·llm
Lovely_Ruby2 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(二),前端项目的开发,对接后端
前端
Cassie燁2 小时前
el-button源码解读4——props color和native-type
vue.js·element
willingtolove2 小时前
使用chrome修改请求参数重新发送请求
前端·chrome
-曾牛2 小时前
CSRF跨站请求伪造:原理、利用与防御全解析
前端·网络·web安全·网络安全·渗透测试·csrf·原理解析
大佐不会说日语~2 小时前
SSE 流式输出 Markdown 实时渲染问题解决方案
java·vue.js·sse·spring ai·前端实时渲染