面试题答案
一键面试- 定义props接收复杂对象:
在Svelte组件中,可以使用类型声明来定义接收的props。假设用户信息对象结构如下:
如果不使用TypeScript,也可以简单定义:// UserInfo.svelte <script lang="ts"> type Address = { street: string; city: string; zip: string; }; type Contact = { phone: string; email: string; }; type User = { name: string; age: number; address: Address; contact: Contact; }; export let user: User; </script>
// UserInfo.svelte <script> export let user; </script>
- 在组件内部使用和处理对象数据:
- 简单展示数据:
<script lang="ts"> type Address = { street: string; city: string; zip: string; }; type Contact = { phone: string; email: string; }; type User = { name: string; age: number; address: Address; contact: Contact; }; export let user: User; </script> <div> <p>Name: {user.name}</p> <p>Age: {user.age}</p> <p>Address: {user.address.street}, {user.address.city}, {user.address.zip}</p> <p>Contact: Phone - {user.contact.phone}, Email - {user.contact.email}</p> </div>
- 处理数据:例如,可以根据用户年龄判断是否成年并展示不同信息。
<script lang="ts"> type Address = { street: string; city: string; zip: string; }; type Contact = { phone: string; email: string; }; type User = { name: string; age: number; address: Address; contact: Contact; }; export let user: User; let isAdult = user.age >= 18; </script> <div> <p>Name: {user.name}</p> {#if isAdult} <p>{user.name} is an adult.</p> {:else} <p>{user.name} is a minor.</p> {/if} </div>
- 简单展示数据: