Home > Web Front-end > Vue.js > What are the ways to obtain DOM nodes in Vue3

What are the ways to obtain DOM nodes in Vue3

WBOY
Release: 2023-05-11 16:55:06
forward
3843 people have browsed it

1. Get the DOM node with native js:

document.querySelector(选择器)
document.getElementById(id选择器)
document.getElementsByClassName(class选择器)
....
Copy after login

2. Get the instance object of the current component in vue2:

Because each vue component instance contains a $refs object , which stores the reference of the corresponding DOM element or component. So by default, the component's $refs points to an empty object.

You can first add ref="name" to the component, and then obtain the corresponding element through this.$refs.name and operate it.

<template>
  <div class="box">
    <h2 ref="divDom">这是一个测试样例</h2>
    <button ref="but">按钮</button>
  </div>
</template>
 
<script>
 
export default {
  data() {
    return {
    }
  },
  methods: {
    showThis(){
      // h2的实例对象 
      console.log(this);
      this.$refs.divDom.style.color=&#39;yellow&#39;
      //引用到组件的实例之后,也可以调用组件上的 methods方法
      this.$refs.but.click();
    },
  },
}
</script>
Copy after login

3. Get the instance object of the current component in vue3:

This object is deactivated in the Vue3 framework, so you cannot use this.$refs to get the custom component ref. DOM node.

But vue3 comes with a function that can return the current component instance object getCurrentInstance. Through this function, you can get the object to save energy and see that the object contains refs in the interface.

<template>
    <div ref="divDom"></div>
</template>
 
<script setup>
    import { ref, getCurrentInstance } from &#39;vue&#39;;
    
    const divDom = ref(null);
    onMounted(()=>{
        console.log(&#39;获取dom元素&#39;,divDom)
    })
 
    // 获取页面的实例对象
    const pageInstance = getCurrentInstance();
    // 获取dom节点对象
    const tagDomObj = pageInstance.refs.divDom;
 
</script>
Copy after login

The above is the detailed content of What are the ways to obtain DOM nodes in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template