Sometimes we have template references, but when using them, the ts prompt does not work, and there is no prompt for the component to pass The method name exposed by defineExpose, although this is not very influential, it can be solved or solved~
<!-- MyModal.vue --> <script setup lang="ts"> import { ref } from 'vue' const sayHello = () => (console.log('我会说hello')) defineExpose({ sayHello }) </script>
Then we use it at the parent level. After entering MyModalRef.value, we will find that there is no sayHello function prompt, so at this time We need to use the InstanceType tool type to get its instance type
<!-- App.vue --> <script setup lang="ts"> import MyModal from './MyModal.vue' const MyModalRef = ref() const handleOperation = () => { MyModalRef.value.sayHello } </script>
Use the InstanceType tool type to get its instance type:
<!-- MyModal.vue --> <script setup lang="ts"> import { ref } from 'vue' const sayHello = () => (console.log('我会说hello')) defineExpose({ open }) </script>
Parent use
<!-- App.vue --> <script setup lang="ts"> import MyModal from './MyModal.vue' const MyModalRef = ref<InstanceType<typeof MyModal> | null>(null) const handleOperation = () => { MyModalRef.value?.sayHello() } </script>
It seems that there is still no prompt to use InstanceType when prompted, and then input the wrong content and no error is reported before compilation..., but Vue official said this, then just listen to him (in fact, I generally don’t use it, but Also learned)
@vue official API annotates component template reference types
Vue3 and TS are definitely the most popular this year front-end technology. Many companies are using Vue3 TS Vite combination to develop new projects. The following is the rewritten sentence: Share how to use Composition-Api combined with TS types in Vue3 components.
Use
When using