Vue 3 获取 DOM
文章目录
- Vue 3 获取 DOM
- 1、方式一:自动绑定
- 代码示例
- 打印结果
- 2、方式二:proxy
- 代码示例
- 打印结果
1、方式一:自动绑定
要求: 要求组件必须有 ref 属性,且变量名必须与 ref 属性值相同!
代码示例
<template>
<div ref="name">
<h1>訾博</h1>
</div>
</template>
<script setup lang="ts">
import {onMounted, ref} from "vue";
// 方式一:自动绑定:要求组件必须有 ref 属性,且变量名必须与 ref 属性值相同
const name = ref<any>();
// 这么写打印的是 undefined ,因为 ref 会在组件渲染完成后才会获取到真实的 DOM 元素
console.log("===setup===")
console.log(name.value);
onMounted(() => {
console.log("===onMounted===")
console.log(name.value);
});
</script>
打印结果
2、方式二:proxy
代码示例
<template>
<div ref="name">
<h1>訾博</h1>
</div>
</template>
<script setup lang="ts">
import { getCurrentInstance, onMounted } from "vue";
// 获取当前实例
const instance = getCurrentInstance();
onMounted(() => {
if (instance) {
const proxy = instance.proxy;
if (proxy) {
console.log(proxy.$refs.name)
}
}
});
</script>
打印结果