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 对象