您的当前位置:首页正文

vue3标签中的ref属性&如何使用$refs获取元素

2024-10-28 来源:个人技术集锦
  • 用在普通DOM标签上,获取的是DOM节点。
  • 用在组件标签上,获取的是组件实例对象。

用在普通DOM标签中

获取dom元素方法一:

<template>    
  <p>{{ person.name }}</p>    
  <!--1.在标签上写上ref属性-->    
  <div ref="msg">{{ person.age }}</div>    
  <p>{{ person.gender }}</p>    
  <button @click="getEle">获取元素</button>    
</template>    

<script setup>    
import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue";

const person = reactive({    
  name: "neko",    
  age: 18,    
  gender: "女",    
});

//2.创建一个引用变量去存储对div标签的引用    
let msg = ref();    

//3.获取元素    
const getEle = () => {    
  console.log(msg.value); // <div>18</div>    
};
</script>    

获取dom元素方法二:

  1. 在需要获取的元素标签上添加ref属性
  2. 通过getCurrentInstance解构出proxy
  3. 通过proxy.$refs.xxx即可获取当前dom元素
<template>           
  <p>{{ person.name }}</p>           
  <!--1.在标签上写上ref属性-->           
  <div ref="msg">{{ person.age }}</div>           
  <p>{{ person.gender }}</p>           
  <button @click="getEle">获取元素</button>           
</template>              

<script setup>              
import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue";

//2.通过getCurrentInstance解构出proxy              
const { proxy } = getCurrentInstance();              

const person = reactive({              
  name: "neko",              
  age: 18,             
  gender: "女",            
});

//3.获取元素         
const getEle = () => {        
  console.log(proxy.$refs.msg); // <div>18</div>       
};
</script>     

用在组件标签上

defineExpose作用:向外暴露属性

<!-- 父组件 -->       
<template>       
  <Demo ref="demoRef"></Demo>       
</template>       

<script setup>       
import { ref, onMounted } from "vue";       
import Demo from "./components/Demo.vue";       

let demoRef = ref();       

onMounted(() => {       
  console.log(demoRef.value);  // 访问子组件Demo中的属性
});
</script>       


<!-- 子组件 -->       
<template>       
  <p>{{ person.name }}</p>       
  <div>{{ person.age }}</div>       
  <p>{{ person.gender }}</p>       
</template>       

<script setup>       
import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue";

const person = reactive({  
  name: "neko", 
  age: 18,
  gender: "女",
});

let num1 = ref(0);
let num2 = ref(1);
let num3 = ref(2);
 <!-- 使用defineExpose将组件中的数据交给外部,这样父组件中的demoRef.value才可以访问到如下数据 -->
defineExpose({ num1, num2, num3, person });
</script>
Top