在Vue 3中,你可以通过以下方式操作DOM:
- 使用
ref
指令获取DOM元素的引用,然后通过引用操作元素,例如:
<template>
<div>
<h1 ref="heading">Hello World!</h1>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const headingEl = ref(null)
// 获取 heading 元素的引用
const getHeadingText = () => {
alert(headingEl.value.innerText)
}
return {
headingEl,
getHeadingText
}
}
}
</script>
- 使用Vue 3提供的
createApp
函数创建应用程序时,可以将一个DOM元素作为应用程序的挂载目标,例如:
<template>
<div>
<h1>Hello World!</h1>
</div>
</template>
<script>
import { createApp } from 'vue'
export default {
beforeMount() {
const app = createApp(this)
// 将应用程序挂载到 `#app` 元素
app.mount('#app')
}
}
</script>
<style>
#app {
background-color: lightblue;
}
</style>