在 vue 中获取节点的方法:直接访问 dom 节点:使用 $el 访问组件根元素。使用 $refs:访问组件的子元素或根元素,需要使用 ref 指定名称。使用渲染函数:在 render 函数中创建元素,并通过 vm.$vnode 访问 dom 节点。使用第三方库:例如 vuetify 和 element ui,可以分别通过 $el 和 $refs 访问 dom 节点。

如何在 Vue 中获取节点?
直接访问 DOM 节点
-
$el: 访问组件根元素。 -
$refs: 访问组件的子元素或根元素,需要在模板中使用ref属性指定名称。
使用渲染函数
- 在
render函数中,使用createElement函数创建元素,并将其作为v-node返回。 - 然后可以通过
vm.$vnode访问v-node,进而获取 DOM 节点。
使用第三方的库
立即学习“前端免费学习笔记(深入)”;
- Vuetify: 提供
$el属性,可以通过this.$el访问 DOM 节点。 - Element UI: 提供
$refs属性,可以通过this.$refs访问 DOM 节点。
示例:
-
直接访问 DOM 节点:
<code class="html"><template> <div id="app">Hello</div> </template> <script> export default { mounted() { console.log(this.$el); // 获取 DOM 节点 <div id="app"> } } </script></code> -
使用渲染函数:
<code class="html"><template> <div>Hello</div> </template> <script> export default { render(h) { return h('div', 'Hello'); }, mounted() { console.log(this.$vnode.elm); // 获取 DOM 节点 <div> } } </script></code> -
使用第三方库:
<code class="html"><template> <v-btn ref="button" @click="handleClick">Button</v-btn> </template> <script> import { Button } from 'vuetify'; export default { components: { Button }, methods: { handleClick() { console.log(this.$refs.button); // 获取 DOM 节点 <button> } } } </script></code>










