标签的ref属性
在 Vue 中,标签的 ref 属性用于获取对 DOM 元素或子组件实例的直接引用。这是一个非常重要的特性,特别是在需要直接操作 DOM 或调用子组件方法时。
基本用法
前置代码
js
<template>
<div class="person">
<h1>IT知识一享</h1>
<h2>学习VUE3</h2>
<button @click="ShowTitle">修改h2元素</button>
</div>
</template>
<script lang="ts" setup>
</script>
<style scoped>
.person{
background-color: rgb(39, 148, 191);
padding-left: 50px;
}
.btn {
display: flex;
gap:20px
}
</style>
- 现在如果我想讲h2的元素内容显示出来,如果去做呢,聪明的你肯定会想到Js中的获取DOM元素的办法
js
function ShowTitle() {
console.log(document.getElementById('titleH2'))
}

- 但是这个会有问题,如果我们的根组件也存在同样的id的话,就会打印根组件的内容
js
<template>
<h2 id="titleH2">根组件</h2>
<Person/>
</template>
<script lang="ts" setup>
import Person from './components/Person.vue'
</script>

- 使用ref标签
js
<template>
<div class="person">
<h1>IT知识一享</h1>
<h2 ref="titleH2">学习VUE3</h2>
<button @click="ShowTitle">修改h2元素</button>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
let titleH2 = ref()
function ShowTitle() {
console.log(titleH2.value)
}
</script>

- 这样就算其他组件有同样的ref标签也不会被影响到,有点局部变量的意思,这个还说一下,这个打印出来有个data-v,这个是因为我们person.vue的样式有scoped属性,他是一个局部样式,所有这个会有一个局部样式的标签;
组件标签中使用ref属性
- 如果在组件标签中使用ref属性的话,可以获取该组件的实例对象
js
<template>
<h2 id="titleH2">根组件</h2>
<Person ref="Per"/>
<button @click="test">测试</button>
</template>
<script lang="ts" setup>
import Person from './components/Person.vue'
import {ref} from 'vue'
let Per = ref()
function test() {
console.log(Per.value);
}
</script>

- 当我们点击测试的时候,拿到的就是person的这个组件实例,但是我们发现我们看不到任何的数据,这是因为Vue3中保护机制,我们需要使用defineExpose暴露给父组件,父组件才能看到它
js
<script lang="ts" setup>
import { ref,defineExpose} from 'vue';
let titleH2 = ref()
function ShowTitle() {
console.log(titleH2.value)
}
defineExpose({titleH2})
</script>
