022、Vue3+TypeScript基础,使用typescript定义并暴露结构,主页面向子页面传递结构数据
01、新建一个index.ts文件,代码如下:
// 定义一个接口,用于限制person对象的具体属性 export interface PersonInter { id: string; name: string; age: number; } export type Persons = Array<PersonInter>;
02、App.vue代码如下:
<template> <div class="app"> <h2>App.Vue</h2> <!-- 使用了ref来获取子组件的属性--> <Person :a1='person' :list1="personList"/> </div> </template> <script lang="ts" setup name="App"> // JS或TS import Person from './view/Person.vue' import type {PersonInter, Persons} from "@/view"; let person: PersonInter = { id: 'a0', name: 'Joker', age: 999, } let personList: Persons = [ { id: 'a001', name: '张三', age: 18, }, { id: 'a002', name: '李四', age: 19, } ] </script> <style scoped> .app { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; } </style>
03、person.vue代码如下:
<template> <div class="person"> <h2>{{ a1 }}</h2> <h2>{{ list1 }}</h2> </div> </template> <script lang="ts" name="Person001" setup> import {defineProps} from 'vue' defineProps(['a1', 'list1']) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
04、效果如下:
05、浏览器运行