为了获得对模板内元素或组件实例的引用,我们可以像往常一样声明 ref 并从 setup() 返回。
组件定义
<template>
<div>说话内容 : {{what}} ...</div>
</template>
<script setup>
import { inject, onMounted, ref } from 'vue'
// 两个参数:需要inject的属性名,默认值(可选)
let what = inject('what', '---');
onMounted(()=>{
setTimeout(()=>{
what.value = 'holl'
},2000);
});
let name = ref('test');
// 定义一个组件内部方法
function saylog(){
console.log('hi, i am log');
}
// 暴露组件方法及属性
defineExpose({
saylog,
name
})
</script>
调用示例
<template>
<say ref="sayCom"></say>
</template>
<script setup>
import { provide, ref, onMounted } from 'vue';
const whatContent = ref('您好');
provide('what', whatContent);
const sayCom = ref(null);
onMounted(()=>{
sayCom.value.saylog();
console.log(sayCom.value.name);
});
</script>