面试题答案
一键面试状态管理方案
- Stores:
- 商品基本信息加载状态:使用一个
writable
store 来管理商品基本信息的加载状态。例如:
- 商品基本信息加载状态:使用一个
import { writable } from'svelte/store';
const productLoadingState = writable('loading');// 初始状态为加载中
// 加载成功时更新
productLoadingState.set('success');
// 加载失败时更新
productLoadingState.set('failed');
- 用户对评论的操作状态:对于评论的点赞和收藏等操作状态,同样可以使用
writable
stores。比如点赞状态:
import { writable } from'svelte/store';
const commentLikeState = writable(false);
// 用户点赞时更新
commentLikeState.set(true);
- LocalStorage 或 IndexedDB:为了实现多个标签页打开同一产品详情时状态的一致性,可以结合
LocalStorage
或IndexedDB
。每当状态发生变化时,将相关状态存储到LocalStorage
或IndexedDB
中。例如对于商品基本信息加载状态:
productLoadingState.subscribe((value) => {
localStorage.setItem('productLoadingState', value);
});
在应用初始化时,从 LocalStorage
或 IndexedDB
中读取状态并初始化 stores:
const storedProductLoadingState = localStorage.getItem('productLoadingState');
if (storedProductLoadingState) {
productLoadingState.set(storedProductLoadingState);
}
与路由集成
- Svelte Router 事件监听:使用 Svelte 路由库(如
svelte - router
),监听路由切换事件。在路由切换时,确保状态的正确传递和更新。例如,当从商品基本信息路由切换到评论路由时,要保证商品基本信息加载状态能被正确携带。
import { onMount } from'svelte';
import { router } from'svelte - router';
onMount(() => {
router.subscribe(({ route }) => {
if (route === '/product/comment') {
// 确保评论操作状态等已正确初始化
const storedCommentLikeState = localStorage.getItem('commentLikeState');
if (storedCommentLikeState) {
commentLikeState.set(JSON.parse(storedCommentLikeState));
}
}
});
});
- 路由参数与状态关联:如果商品基本信息的加载依赖于路由参数(如商品 ID),可以在路由参数变化时触发商品基本信息的加载操作,并更新加载状态。
import { page } from '$app/stores';
import { productLoadingState } from './stores.js';
$: page.subscribe(({ params }) => {
const productId = params.productId;
// 触发商品基本信息加载
productLoadingState.set('loading');
// 加载逻辑,加载完成后更新状态
setTimeout(() => {
productLoadingState.set('success');
}, 2000);
});
通过上述状态管理方案和与路由的集成,可以在多层嵌套路由且涉及多个组件间数据交互的 Svelte 应用中,满足在不同子路由切换过程中保持相关状态,以及多个标签页状态一致性的需求。