编译宏 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   ChoZ  阅读(6)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-02-22 Vue3中使用JSX简明语法
2023-02-22 TS补充笔记

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示