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

What are the ways to obtain DOM nodes in Vue3

WBOY
WBOYforward
2023-05-11 16:55:063739browse

1. Get the DOM node with native js:

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

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>

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>

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete