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>