Home > Web Front-end > Vue.js > How to get dom in vue

How to get dom in vue

下次还敢
Release: 2024-04-30 05:36:17
Original
721 people have browsed it

In Vue.js, you can obtain DOM elements in four ways: use ref to create a reference for a component or DOM element; obtain DOM elements based on CSS selectors through querySelector; obtain DOM element bounding rectangle information through getBoundingClientRect; Use event.target to get the DOM element that triggered the event when the event occurs.

How to get dom in vue

Getting DOM in Vue

In Vue.js, there are several ways to get DOM elements, depending on the for actual needs.

1. Create a reference to the component or DOM element through the ref

ref attribute. Within a component, references can be accessed using this.$refs. For DOM elements, you can use $refs to access DOM nodes.

<code class="javascript">// 组件中
<template>
    <div ref="myDiv"></div>
</template>
<script>
export default {
    mounted() {
        console.log(this.$refs.myDiv); // 获取 myDiv DOM 节点
    }
}
</script>

// DOM 元素
<div ref="myDiv"></div>
<script>
console.log(document.myDiv); // 获取 myDiv DOM 节点
</script></code>
Copy after login

2. Use the querySelector

##querySelector method to get DOM elements based on CSS selectors.

<code class="javascript">// 组件中
const myDiv = this.$el.querySelector('div');

// DOM 元素
const myDiv = document.querySelector('div');</code>
Copy after login

3. Return a DOMRect object containing the bounding rectangle information of the DOM element through the getBoundingClientRect

getBoundingClientRect method.

<code class="javascript">// 组件中
const rect = this.$el.getBoundingClientRect();

// DOM 元素
const rect = document.myDiv.getBoundingClientRect();</code>
Copy after login

4. Pass event.target

When an event occurs, the

event.target property contains the DOM element that triggered the event.

<code class="javascript">// 在事件处理函数中
const target = event.target;</code>
Copy after login
Depending on the specific situation, you can choose the most appropriate method to obtain DOM elements based on the above methods.

The above is the detailed content of How to get dom in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template