document.querySelector(选择器) document.getElementById(id选择器) document.getElementsByClassName(class选择器) ....
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='yellow' //引用到组件的实例之后,也可以调用组件上的 methods方法 this.$refs.but.click(); }, }, } </script>
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 'vue'; const divDom = ref(null); onMounted(()=>{ console.log('获取dom元素',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!