PHP前端开发

vue中怎么获取dom元素

百变鹏仔 3周前 (09-25) #VUE
文章标签 元素
在 vue 中,获取 dom 元素有三种方法:1. 使用 ref 属性为元素指定引用变量,并通过 this.$refs 访问;2. 直接使用组件的根元素 this.$el;3. 使用 queryselector 方法在绑定元素上查询。

在 Vue 中获取 DOM 元素

在 Vue 应用中,可以通过以下方法获取 DOM 元素:

1. ref 属性

<template><div ref="myDiv"></div></template><script>import { ref } from 'vue'export default {  setup() {    const myDiv = ref(null)  // 声明一个空引用变量    return { myDiv }  },  mounted() {    console.log(this.$refs.myDiv)  // myDiv 元素  }}</script>

2. $el 属性

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

<template><div></div></template><script>import { ref } from 'vue'export default {  setup() {    const myDiv = ref(null)  // 声明一个空引用变量    return { myDiv }  },  mounted() {    console.log(this.$el)  // 组件的根元素  }}</script>

3. querySelector

<template><div></div></template><script>import { ref } from 'vue'export default {  setup() {    // 绑定一个空引用变量    const myDiv = ref(null)    return { myDiv }  },  mounted() {    this.myDiv.value = this.$el.querySelector('div')  }}</script>