Vue $el 物件
示例
使用 $el
物件更改根級別的 <div>
標籤的背景顏色。
methods: {
changeColor() {
this.$el.style.backgroundColor = 'lightgreen';
}
}
執行示例 »
更多示例請參見下方。
定義和用法
$el
物件表示 Vue 元件的根 DOM 節點。
Vue 應用程式掛載之前,$el
物件不存在。
如果 <template> 中只有一個 HTML 根元素
- 則
$el
物件就是那個根元素。 - 可以使用
$el
物件直接操作 DOM(請參見上面的示例),但不推薦這樣做。 - 最好使用 Vue 的
ref
屬性和其他 Vue 功能以宣告式方式更改 DOM,因為它能使程式碼更一致且易於維護(請參見下面的示例 1)。
如果 <template> 中有多個 HTML 根元素
- 則
$el
物件將僅僅是一個 Vue 內部使用的佔位符 DOM 文字節點(而不是實際的 DOM 元素)。 - 在這種情況下,DOM 不能 使用
$el
物件進行操作(請參見下面的示例 2)。
注意:在 Vue 3 的 Composition API 中,在 <script setup>
(使用 setup
函式)中無法訪問 $el
屬性。
更多示例
示例 1
使用 ref
屬性以推薦的方式宣告式地更改 <div>
標籤的背景顏色,而不是使用 $el
物件。
<template>
<div ref="rootDiv">
<h2>Example $el Object</h2>
<p>It is recommended, and more consistent, to use the ref attribute instead of the $el object to change the background color root DIV tag.</p>
<button v-on:click="changeColor">Click here</button>
</div>
</template>
<script>
export default {
methods: {
changeColor() {
this.$refs.rootDiv.style.backgroundColor = 'lightgreen';
}
}
}
</script>
執行示例 »
示例 2
當 <template> 的根中有多個元素時,$el
物件將僅僅是 Vue 內部使用的第一個根元素的文字節點表示(而不是實際的 DOM 元素)。
在這種情況下,我們不能使用 $el
物件來操作 DOM。
<template>
<div>
<h2>Example $el Object</h2>
<p>We are not able to use the $el object to change the background color of the root DIV tag when there are other tags on the root level. Open browser console to see the error generated.</p>
<button v-on:click="changeColor">Click here</button>
</div>
<p>With this extra p-tag there are two tags on the root level.</p>
</template>
<script>
export default {
methods: {
changeColor() {
this.$el.style.backgroundColor = 'lightgreen';
}
}
}
</script>
<style>
#app > div, #app > p {
border: solid black 1px;
padding: 10px;
}
</style>
執行示例 »
示例 3
使用 $el
物件更改 <h2>
子元素的背景顏色。
<template>
<div>
<h2>Example $el Object</h2>
<p>Using the $el object to change the background color of the H2 child element.</p>
<button v-on:click="changeColor">Click here</button>
</div>
</template>
<script>
export default {
methods: {
changeColor() {
this.$el.children[0].style.backgroundColor = 'lightblue';
}
}
}
</script>
執行示例 »
相關頁面
Vue 教程:Vue Template Refs
Vue 教程: Vue 方法
Vue 參考:Vue 'ref' 屬性
Vue 參考:Vue $refs 物件