vue3.3优化了defineProps和defineEmits写法

456 阅读1分钟

针对defineProps的优化

  • 父组件调用
<template>
  <A :child="['yx']"></A>
</template>

<script setup lang="ts">

import A from './A.vue'

</script>

  • 子组件
普通方法获取props 传递过来的之
<template>
  <div>
    A component --- {{child}}
  </div>
</template>

<script setup lang="ts" name="A">

import { PropType } from 'vue'

// 普通方法
const props = defineProps({
    child:{
        type: Array as PropType<string[]>,
        required:true
    }
})
// 为 unkonw 缺少类型提示 为了解决这个问题 vue 提供了一个 propType 类型
// 添加了 PropType 后 props.child 会推断成 string类型数组
props.child

</script>

ts 泛型字面量获取 props 传递过来的值
/*  *** */

<script setup lang="ts" name="A">

// ts 泛型字面量方法
const props = defineProps<{
    child:string[]
}>()

props.child

</script>
vue3.3 对 defineProps的改进,新增泛型支持需要在script标签上加 generic=“T”,T为泛型
/*  **  */
<script generic="T" setup lang="ts" name="A">

// vue3.3 对 defineProps的改进,新增泛型支持需要在script标签上加 generic=“T”,T为泛型
// 如父组件传递过来刚开始是string,后面改成number,boolean等,子组件不用跟着改变
const props = defineProps<{
    child:T[]
}>()

props.child

</script>

defineEmits优化

  • 父组件
<template>

  <A @send="getName"></A>
</template>

<script setup lang="ts">

import A from './A.vue'

const getName = (child)=>{
  console.log('child:',child)
}

</script>
  • 子组件
<template>
  <button @click="send">验证emit</button>
</template>

普通函数defineEmits调用
<script setup lang="ts" name="A">

// 普通方法定义一个send方法
const emits = defineEmits(['send'])

const send = ()=>{
    emits('send','hello yx')
}
ts 写法
<script setup lang="ts" name="A">

// ts 写法
const emits = defineEmits<{
    // event 类似于形参数, name 是函数 的形参
    (event:string,name:string):void
}>()
const send = ()=>{
    emits('send','hello yx')
}

</script>
vue3.3 写法更加精简
<script setup lang="ts" name="A">

const emits = defineEmits<{
        'send':[name:string]
}>()

const send = ()=>{
    emits('send','hello yx')
}
</script>