首先给dom元素用ref=""命名
然后声明在setup中一个响应式变量,这个变量的名字要和ref命名一致,最后返回这个变量
重要:要想获取这个dom必须在onMounted中,因为setup替代了原来的created
A.vue
<template>
<p>这是A页面</p>
</template>
<script setup>
const str = ref("我是A组件的数据");
const btn = () => {
alert("hello");
};
defineExpose({ str, btn });
</script>
App.vue
<template>
<h1>hello vue3</h1>
<A ref="ref_A" />
<button @click="ref_A.btn()">调用暴露出来的方法-方式1</button>
<button @click="test">调用暴露出来的方法-方式2</button>
</template>
<script setup>
import A from "@/components/A.vue";
const ref_A = ref(null);
function test() {
ref_A.value.btn();
}
onMounted(() => {
console.log(ref_A.value);
console.log(ref_A.value.str);
});
</script>