web前端全系列 教程
1839个小节阅读:2243k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
当使用 <script setup>
时,defineProps()
宏函数支持从它的参数中推导类型
xxxxxxxxxx
<template>
<h3>列表</h3>
<p>{{ props.title }}</p>
<p>{{ props.text }}</p>
</template>
<script setup lang="ts">
const props = defineProps({
title:{
type:String,
required:true
},
text:String
})
</script>
然而,通过泛型参数来定义 props 的类型通常更直接
xxxxxxxxxx
<template>
<h3>列表</h3>
<p>{{ props.title }}</p>
<p>{{ props.text }}</p>
</template>
<script setup lang="ts">
const props = defineProps<{
title:string,
text:string
}>()
</script>
我们也可以将 props 的类型移入一个单独的接口中
xxxxxxxxxx
<template>
<h3>列表</h3>
<p>{{ props.title }}</p>
<p>{{ props.text }}</p>
</template>
<script setup lang="ts">
interface Props{
title:string,
text:string
}
const props = defineProps<Props>()
</script>
xxxxxxxxxx
<template>
<h3>列表</h3>
<p>{{ props.book.name }}</p>
<p>{{ props.book.author }}</p>
</template>
<script setup lang="ts">
interface iBook{
name:string;
author:string;
}
const props = defineProps<{
book: iBook
}>()
</script>
为了生成正确的运行时代码,传给 defineProps()
的泛型参数必须是以下之一:
defineProps<{ /*... */ }>()
interface Props {/* ... */}
传递给 defineProps
的泛型参数本身不能是一个导入的类型
xxxxxxxxxx
import { Props } from './home-types'
// 不支持!
defineProps<Props>()
这是因为 Vue 组件是单独编译的,编译器目前不会抓取导入的文件以分析源类型。我们计划在未来的版本中解决这个限制
当使用基于类型的声明时,我们失去了为 props 声明默认值的能力。这可以通过 withDefaults
编译器宏解决
xxxxxxxxxx
<template>
<h3>列表</h3>
<p>{{ props.title }}</p>
<p>{{ props.text }}</p>
</template>
<script setup lang="ts">
interface Props{
title?:string,
text?:string
}
const props = withDefaults(defineProps<Props>(),{
title:"itbaizhan",
text:"test"
})
</script>