MST

星途 面试题库

面试题:Svelte组件化开发中如何传递和处理复杂对象类型的props

在Svelte组件化开发里,假设你有一个组件需要接收一个包含多层嵌套的复杂对象作为props,例如一个表示用户信息的对象,其中包含地址、联系方式等嵌套对象。请描述你会如何在接收组件中定义props来接收这个复杂对象,以及如何在组件内部使用和处理这个对象的数据。
20.4万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 定义props接收复杂对象: 在Svelte组件中,可以使用类型声明来定义接收的props。假设用户信息对象结构如下:
    // 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>
    
    如果不使用TypeScript,也可以简单定义:
    // UserInfo.svelte
    <script>
        export let user;
    </script>
    
  2. 在组件内部使用和处理对象数据
    • 简单展示数据
      <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>