Vue $el 对象
实例
使用 $el 对象更改根级别上 <div> 标记的背景颜色。
methods: {changeColor() {this.$el.style.backgroundColor = 'lightgreen';}}
定义与用法
$el 对象表示 Vue 组件的根 DOM 节点。
$el 对象在 Vue 应用程序安装之前不存在。
如果 <template> 中只有一个 HTML 根元素
- $el 对象将是该根元素。
- DOM 可以直接使用 $el 对象进行操作(请参阅上面的实例),但不建议这样做。
- 最好使用 Vue
ref属性和其他 Vue 功能以声明方式更改 DOM,因为这会导致代码更加一致,更易于维护(请参见下面的实例1)。
如果 <template> 中有多个 HTML 根元素:
- $el 对象将只是 Vue 内部使用的占位符 DOM 文本节点(而不是实际的 DOM 元素)。
- 当存在多个根元素时,不能使用 $el 对象来操作 DOM(请参见下面的实例2)。
注意:在 Vue 3 的 Composition API 中,
$el 属性在 <script setup> 中不可访问(使用 setup 函数)。更多实例
实例 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 元素)。所以会出错。
<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>