复制代码
1, src/components/Person.vue
<template>
<div class="person">
<ul>
<li v-for="item in list" :key="item.id">
{{ item.name }}--{{ item.age }}
</li>
</ul>
</div>
</template>
<script setup lang="ts" name="Person">
import {defineProps, withDefaults } from 'vue';
import {type Persons} from '@/types'
// 接收list
// defineProps(['list'])
// 接收list + 限制类型 校验
// defineProps<{list:Persons}>()
// 接收list + 限制类型 + 限制必要性 + 指定默认值
withDefaults(defineProps<{list?:Persons}>(),{
list: () => [
{id:'zg01',name:'康师傅',age:18},
{id:'zg02',name:'龙辛拉面',age:20}
]
})
// 接收list同时将props保存起来
// let props = defineProps(['list'])
// 接收a,b同时将props保存起来
// let props = defineProps(['a','b'])
// console.log(props.a);
// console.log(props.b);
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
li {
font-size: 20px;
}
</style>
2, src/App.vue
<template>
<!-- 务必看懂下面这行代码 -->
<!-- <h2 a="1+1" :b="1+1" c="x" :d="x" ref="qwe">测试</h2> -->
<Person a="哈哈" />
</template>
<script setup lang="ts" name="App">
import Person from '@/components/Person.vue';
import {reactive} from 'vue'
import {type Persons} from '@/types/index'
let x = 10;
let personList = reactive<Persons>([
{id: 'axs01', name: '张三',age: 23},
{id: 'axs02', name: '李四',age: 24},
{id: 'axs03', name: '王五',age: 25},
{id: 'axs04', name: '赵六',age: 26}
])
// console.log(personList);
</script>
<style scoped>
.app {
background-color: #ddd;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
3, src/types/index.ts
// 定义一个接口,用于限制person对象的具体属性和类型
// PersonInter是自定义接口,限制一个人的,id,name,age三个属性,分别是字符串和数字类型
export interface PersonInter {
id : string,
name : string,
age : number,
sex? : string
}
// 一个自定义类型,用于限制person对象的具体属性和类型
// Persons是自定义类型,限制一堆人的
// 第一种写法 泛型
// export type Persons = Array<PersonInter>
// 第二种写法 自定义类型
export type Persons = PersonInter[]
4, src/main.ts
// 引入 createApp 用于创建应用
import {createApp} from 'vue'
// 引入 App根组件
import App from './App.vue'
// 调用createApp()方法创建应用并放在id为app的容器里面
createApp(App).mount('#app')
5, index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>