- Used on ordinary DOM tags, the DOM node is obtained.
- Used on the component tag, the component instance object is obtained.
Used in ordinary DOM tags
Method 1 to obtain dom element:
- Add ref attribute on the element tag you want to get
- Create a ref object and store the contents of the ref attribute tag
- The current dom element can be obtained through the value attribute on the ref
<template> <p>{{ }}</p> <!--1.Write on the tagrefproperty--> <div ref="msg">{{ }}</div> <p>{{ }}</p> <button @click="getEle">Get elements</button> </template> <script setup> import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; const person = reactive({ name: "neko", age: 18, gender: "female", }); //2. Create a reference variable to store references to div tagslet msg = ref(); //3. Get elementsconst getEle = () => { (); // <div>18</div> }; </script>
Method 2 to obtain dom element:
getCurrentInstance(): Get the current component instance
- Add ref attribute on the element tag you want to get
- Deconstructing proxy by getCurrentInstance
- Get the current dom element through proxy.$
<template> <p>{{ }}</p> <!--1.Write on the tagrefproperty--> <div ref="msg">{{ }}</div> <p>{{ }}</p> <button @click="getEle">Get elements</button> </template> <script setup> import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; //2. Deconstruct the proxy through getCurrentInstanceconst { proxy } = getCurrentInstance(); const person = reactive({ name: "neko", age: 18, gender: "female", }); //3. Get elementsconst getEle = () => { (proxy.$); // <div>18</div> }; </script>
Used on component labels
defineExpose function: expose properties outward
<!-- Parent component --> <template> <Demo ref="demoRef"></Demo> </template> <script setup> import { ref, onMounted } from "vue"; import Demo from "./components/"; let demoRef = ref(); onMounted(() => { (); // Access properties in child component demo}); </script> <!-- Subcomponents --> <template> <p>{{ }}</p> <div>{{ }}</div> <p>{{ }}</p> </template> <script setup> import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; const person = reactive({ name: "neko", age: 18, gender: "female", }); let num1 = ref(0); let num2 = ref(1); let num3 = ref(2); <!-- usedefineExposeHand over the data in the component to the outside,这样Parent component中的才可以访问到如下数据 --> defineExpose({ num1, num2, num3, person }); </script>
Summarize
This is the article about the detailed explanation of the ref attribute in the vue3 tag and how to use $refs to obtain elements. For more related vue3 $refs to obtain elements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!