ref

You can define a subcomponent and want to get a method or instance of the subcomponent through ref if ts compilation fails

Child components:

//son.vue

<template>
    <h1>son</h1>
</template>

<script lang="ts" setup>
const count = 0

const fn = () => {
    console.log(' -- -- -- -- -- -- -- -- -- -- - the method of child components -- -- -- -- -- -- -- -- -- -- - ')} defineExpose ({fn, count}) < / script >Copy the code

The parent component:

//father.vue

<template>
    <Son ref="sonRef" />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import Son from './son.vue'

interface sonData {
    fn: () => void
    count: number
}

const sonRef = ref<InstanceType<typeof Son> & sonData>()

const a = onMounted(() => {
    console.log(sonRef.value? .$el) console.log(sonRef.value?.fn)
})

</script>
Copy the code

If you want to get the methods of the child component’s data, delete the InstanceType<typeof Son>.

defineProps

DefineProps is a function provided in vue3 Setup. In normal writing, there is no type indication, which means that errors are not reported.

I provide two ways to write it, one is for generics and the other is for defining values.

interface Form {
    age: number
    name:string
}

const props = defineProps<{
    msg: stringform? : Form }>()Copy the code
import { PropType } from 'vue'

defineProps({
    msg: {
        type: String.required: true,},form: {
        type: Object as PropType<Form>,
        required: false.default() {
            return {
                age: 99999,}},},})Copy the code

Both of these are good code prompts, but the first is more succinct and doesn’t set defaults. The second can be set to a default value.

defineEmits

defineEmits is the same reason, can not get a good event tips.

const emits = defineEmits<{
    (e: 'emits'.data: number) :void
    (e: 'ws'.data: string) :void} > ()const emit = () = > {
    emits('ws'.'27')}Copy the code

That’s how you get a good code hint