JavaScript/vue.js/ref
来自康健生活
< JavaScript | vue.js
引言
- 在普通的元素上,this.ref.name 获取到的是 dom 元素
- 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法
引用 DOM
组件内 DOM
<template>
<div ref="dom">Hello, Vue 3 with TypeScript!</div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
...
const dom = ref<HTMLDivElement | null>(null);
onMounted(() => {
if (dom.value) console.log(dom.value);
});
...
</script>
组件
<template>
<ChildComponent ref="comp" />
</template>
<script lang="ts" setup>
import { ref, onMounted, type InstanceType } from 'vue';
import ChildComponent from './ChildComponent.vue';
...
// 类型推断 InstanceType<T>
const comp = ref<InstanceType<typeof ChildComponent> | null>(null);
onMounted(() => {
if (comp.value) console.log(comp.value);
});
...
</script>
函数
No categories