<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>
<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>