编译宏 definedProps、definedEmits、definedOptions、definedSlot

<template>
<div>{{prop.dataProp}}</div>
{{ a }}{{ b }}
<div v-for="item in prop.dataProp" :key="String(item)">
  {{ item }}
  <slot :item="item"></slot>
</div>
<button @click="update">update</button>
</template>

<script setup lang='ts' generic="T">
// 使用generic="T"来接收父组件传进来的泛型数据

// import type { PropType } from 'vue';
// 接收父组件传进来泛型的数据
// 1.常规写法,需要使用PropType
// const prop = defineProps({
//   dataProp: Array // 但是这种形式不会提示类型
//   dataProp: Array as PropType<string[]>
// })
// 2.在明确使用泛型的类型时,可以使用以下方法
// const prop = defineProps<{
//   dataProp: string[]
// }>()
// 3.在不明确传来数组的类型时,可以使用以下方法
const prop = defineProps<{
  dataProp: T[]
}>()

// definedEmits的不同写法
// 1.常规写法
// const emit = defineEmits(['update'])
// 2.使用Ts的写法
// const emit = defineEmits<{
//   (event: 'update',name: string): void
// }>()
// 3.升级精简版
const emit = defineEmits<{
  'update': [name: string] 
}>()
const update = () => {
  emit('update', 'hello')
}

// 3.3之后才支持的写法
// 作用主要是定义name属性,因为setup中的name属性是不生效的,写法跟vue2的写法一样
// 例如在里面定义的data可以直接使用,虽然提示报错,但不影响使用
defineOptions({
  name: 'Child',
  data() {
    return {
      a:1,
      b:2
    }
  },
})

// 只有声明没有实现,只能定义来限制当前文件的slot的参数类型和返回值类型
defineSlots<{
  // 限制匿名组件的porp只能传入属性名为item的T类型的数据
  default(prop: {item: T}): void
}>()
</script>

<style scoped lang='scss'>

</style>
<template>
  <Child :dataProp="dataProp"></Child>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue'
import Child from '../studyVue/defined/component.vue'
const dataProp = ref(['1', '2', '3'])
</script>

<style scoped lang='scss'>

</style>

 

posted on 2025-02-22 22:23  ChoZ  阅读(87)  评论(0)    收藏  举报

导航