面试题答案
一键面试- 定义类型:
- 首先,定义用户信息的类型。假设用户信息包含姓名、年龄和地址,地址又包含省、市、区。
// 定义地址类型 type Address = { province: string; city: string; district: string; }; // 定义用户信息类型 type UserInfo = { name: string; age: number; address: Address; };
- 在Pinia中使用类型:
- 安装
pinia
并在Vue项目中引入。 - 创建一个Pinia store来管理用户信息。
import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ({ user: {} as UserInfo }), actions: { // 获取用户信息 getInfo() { // 假设这里是从后端获取数据 // 这里模拟数据返回 this.user = { name: 'John', age: 30, address: { province: 'Guangdong', city: 'Shenzhen', district: 'Nanshan' } }; }, // 修改用户信息 updateInfo(newInfo: UserInfo) { this.user = newInfo; }, // 修改地址中的省 updateProvince(province: string) { this.user.address.province = province; } } });
- 安装
- 在组件中使用:
- 在Vue组件中使用这个Pinia store。
<template> <div> <button @click="getUserInfo">获取用户信息</button> <button @click="updateUserInfo">更新用户信息</button> <button @click="updateProvince">更新省份</button> </div> </template> <script setup lang="ts"> import { useUserStore } from '@/stores/user'; const userStore = useUserStore(); const getUserInfo = () => { userStore.getInfo(); }; const updateUserInfo = () => { const newInfo: UserInfo = { name: 'Jane', age: 25, address: { province: 'Jiangsu', city: 'Nanjing', district: 'Gulou' } }; userStore.updateInfo(newInfo); }; const updateProvince = () => { userStore.updateProvince('Zhejiang'); }; </script>
通过以上步骤,在获取和修改嵌套状态时,TypeScript能确保类型安全性,在编译阶段就能检测到类型错误。