PHP前端开发

vue怎么获取节点

百变鹏仔 3周前 (09-25) #VUE
文章标签 节点
vue 中获取节点的方法包括:$refs 属性、template ref、createelement 方法、document.queryselector 方法、queryselectorall 方法。通过这些方法,开发者可以获取组件实例的 dom 节点引用、直接获取模板中 dom 节点的引用、创建并附加新的 dom 节点、使用 css 选择器获取节点,或获取所有满足选择器的节点。

Vue 中获取节点的方法

在 Vue 中获取 DOM 节点提供了多种方法,下面将逐一介绍这些方法。

1. $refs

$refs 属性允许您获取组件实例的 DOM 节点引用。它的用法如下:

立即学习“前端免费学习笔记(深入)”;

<template><div ref="my-ref"></div></template><script>export default {  mounted() {    const myRef = this.$refs['my-ref'];    // 操作 DOM 节点  }}</script>

2. template ref

使用 template ref 语法,可以在模板中直接获取 DOM 节点的引用。它的用法如下:

<template><div ref="my-ref"></div></template><script>export default {  mounted() {    this.$refs['my-ref'].focus();    // 操作 DOM 节点  }}</script>

3. createElement

createElement 方法可以创建新的 DOM 节点并将其附加到现有节点。它的用法如下:

<template><div id="app"></div></template><script>export default {  mounted() {    const newElement = this.$createElement('div', { attrs: { id: 'my-new-element' } });    this.$el.appendChild(newElement);  }}</script>

4. document.querySelector

document.querySelector 方法可用于获取满足给定 CSS 选择器的第一个匹配 DOM 节点。它的用法如下:

<script>export default {  mounted() {    const myElement = document.querySelector('#my-element');    // 操作 DOM 节点  }}</script>

5. querySelectorAll

querySelectorAll 方法可用于获取满足给定 CSS 选择器的所有匹配 DOM 节点。它的用法如下:

<script>export default {  mounted() {    const myElements = document.querySelectorAll('.my-elements');    // 操作 DOM 节点  }}</script>