Custom Components
<template>
<div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
console.log('11')
return '22';
}
</script>
Copy the code
Use custom components
<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>
Copy the code
The thinking of VUe2, written this way, will report errors.
TypeError: child.value.testLog is not a function
Copy the code
Change it to the following, and that’s it.
Custom Components (final version)
<template>
<div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
console.log('11')
return '22';
}
// Expose
defineExpose({
testLog
})
</script>
Copy the code
Vue3’s custom components, such as methods and functions, are not external by default. If you need external calls, you need to use method functionsdefineExpose
Expose it.
Vue version: 3.1.4