文章目录
- 基本用法
ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的
$refs
对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件
基本用法
<!-- 存储为 this.$refs.p -->
<p ref="p">hello</p>
- 使用组合式 API,引用将存储在与名字匹配的 ref 里:
<script setup>
import { ref } from 'ref="/tags/VUE.html" title=vue>vue'
const p = ref()
</script>
<template>
<p ref="p">hello</p>
</template>
- 可以接收一个函数值,用于对存储引用位置的完全控制:
<ChildComponent :ref="(el) => child = el" />
- 模板引用也可以被用在一个子组件上。这种情况下引用中获得的值是组件实例:
<script>
import Child from './Child.ref="/tags/VUE.html" title=vue>vue'
export default {
components: {
Child
},
mounted() {
// this.$refs.child 是 <Child /> 组件的实例
}
}
</script>
<template>
<Child ref="child" />
</template>