JavaScript/vue.js/ref:修订间差异
来自康健生活
创建页面,内容为“== 引言 == * 在普通的元素上,this.ref.name 获取到的是 dom 元素 * 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的…” |
|||
| 第2行: | 第2行: | ||
* 在普通的元素上,this.ref.name 获取到的是 dom 元素 | * 在普通的元素上,this.ref.name 获取到的是 dom 元素 | ||
* 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法 | * 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法 | ||
== 引用 DOM == | |||
=== 组件内 DOM === | |||
<syntaxhighlight lang="html5"> | |||
<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> | |||
</syntaxhighlight> | |||
=== 组件 === | |||
<syntaxhighlight lang="html5"> | |||
<template> | |||
<ChildComponent ref="comp" /> | |||
</template> | |||
<script lang="ts" setup> | |||
import { ref, onMounted, type InstanceType } from 'vue'; | |||
import ChildComponent from './ChildComponent.vue'; | |||
... | |||
const comp = ref<InstanceType<typeof ChildComponent> | null>(null); | |||
onMounted(() => { | |||
if (comp.value) console.log(comp.value); | |||
}); | |||
... | |||
</script></syntaxhighlight> | |||