Home > Web Front-end > Vue.js > How to solve the problem of vue3 getting ref instance combined with ts InstanceType

How to solve the problem of vue3 getting ref instance combined with ts InstanceType

WBOY
Release: 2023-05-20 22:59:32
forward
1750 people have browsed it

    vue3 Gets the ref instance and combines it with the InstanceType of ts

    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 &#39;vue&#39;
    
    const sayHello = () => (console.log(&#39;我会说hello&#39;))
    
    defineExpose({
      sayHello
    })
    </script>
    Copy after login

    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 &#39;./MyModal.vue&#39;
    const MyModalRef = ref()
    
    const handleOperation = () => {
      MyModalRef.value.sayHello
    }
    </script>
    Copy after login

    How to solve the problem of vue3 getting ref instance combined with ts InstanceType

    Use the InstanceType tool type to get its instance type:

    <!-- MyModal.vue -->
    <script setup lang="ts">
    import { ref } from &#39;vue&#39;
    
    const sayHello = () => (console.log(&#39;我会说hello&#39;))
    
    defineExpose({
      open
    })
    </script>
    Copy after login

    Parent use

    <!-- App.vue -->
    <script setup lang="ts">
    import MyModal from &#39;./MyModal.vue&#39;
    
    const MyModalRef = ref<InstanceType<typeof MyModal> | null>(null)
    
    const handleOperation = () => {
      MyModalRef.value?.sayHello()
    }
    </script>
    Copy after login

    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

    How to annotate TS types for vue3 components

    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.

    Annotate the type for props

    Use

    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template