-
定义类型(src/types/index.ts)
?代表可有可无export interface Persons { id: number, name: string, age?: number }
-
定义Person子组件(src/components/Person.vue)
<template> <ul> <li v-for="item in list" :key="item.id"> {{item.name}} --- {{item.age}} </li> </ul> </template>
<script setup lang="ts"> import type {Persons} from '@/types'; import {withDefaults} from 'vue'; // 单纯的获取父级传过来的list defineProps(['list']); // 获取list,并限制类型 defineProps<{list: Persons[]}>(); // 获取list,并设置不必填 defineProps<{list?: Persons[]}>(); // 获取list,并设置默认值 withDefaults(defineProps<{list?: Persons[]}>(), { list: () => [{id: 999, name: '我是默认值', age: 20}] }); </script>
-
定义App父组件(src/App.vue)
<template> <Person :list="PersonList"/> </template>
<script setup lang="ts"> import Person from '@/components/Person.vue'; import {reactive} from 'vue'; import type {Persons} from '@/types'; const PersonList = reactive<Persons[]>([ {id: 1, name: '张三', age: 18}, {id: 2, name: '李四', age: 19}, {id: 3, name: '王五', age: 20} ]); </script>
vue3中ts的基本用法
最新推荐文章于 2024-07-07 21:39:35 发布