使用vue3如何操作DOM元素?

6 min read

在Vue 3中,你可以通过以下方式操作DOM:

  1. 使用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>
  1. 使用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>