自定义组件
<template>
<div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
console.log('11')
return '22';
}
</script>
使用自定义组件
<template>
<div>
<test-a ref="child"/>
<button @click="testClick">test</button>
</div>
</template>
<script lang="ts" setup>
import {ref} from "vue";
const child = ref<any>();
const testClick = () => {
//child.value.testLog();
console.log(child.value.testLog())
}
</script>
vue2的思维,这样写,是会报错的。
TypeError: child.value.testLog is not a function
修改为下面的,就可以了。
自定义组件(最终版)
<template>
<div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
console.log('11')
return '22';
}
// 暴露出去
defineExpose({
testLog
})
</script>
意思就是,vue3的自定义组件里,方法函数等,默认是不对外的,如果需要外部调用,就需要将方法函数使用 defineExpose 暴露出去。
vue版本:3.1.4