<script setup lang="ts">
import { ref } from 'vue'
const dom = ref<HTMLDivElement>()
function change() {
console.log(dom.value?.innerText)
}
</script>
<template>
<div>
<button @click="change">change</button>
<div ref="dom">Hello Meowrain</div>
</div>
</template>
<style></style>
在元素上添加ref="变量名"
,script中写const dom = ref<HTMLDivElement>()
,因为采用了setup语法糖,如果直接写在script标签中,得到的结果就是undefined,只有在函数中才能调用.