在 Vue.js 中,ref
是一个特殊的属性,它允许我们为元素或子组件注册一个引用信息。引用信息将会注册在父组件的 $refs
对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例。
1.普通DOM上使用
<template>
<div>
<h2 ref="title">HelloWorld</h2>
<button @click="print">打印</button>
</div>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
let title = ref()
function print(){
console.log(title.value)
}
</script>
2.子组件上使用
// HelloWorld.vue
<template>
<div>
<h2 ref="title">HelloWorld</h2>
<button @click="print">打印</button>
</div>
</template>
<script lang="ts" setup>
import {ref, defineExpose} from 'vue'
let title = ref()
function print(){
console.log(title.value)
}
let a = ref(1)
// 暴露给父组件,父组件才可以使用
defineExpose({a})
</script>
// App.vue
<template>
<HelloWorld ref="child"/>
<button @click="fatherPrint">父组件打印</button>
</template>
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue';
import { ref } from 'vue';
let child = ref();
function fatherPrint() {
console.log('fatherPrint', child.value);
console.log('child.a', child.value.a);
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>