实现思路
- 使用存储管理:可以使用 Svelte 的
writable
来创建一个可写的存储,该存储在不同组件间共享,这样无论页面如何切换,存储中的数据都能保持状态。
- 路由切换处理:在路由切换过程中,不重新初始化
PageA
组件中依赖该变量的部分,而是直接从共享存储中读取数据。
关键代码示例
- 创建共享存储
// stores.js
import { writable } from'svelte/store';
export const countStore = writable(0);
- PageA 组件
// PageA.svelte
<script>
import { countStore } from './stores.js';
let count;
countStore.subscribe((value) => {
count = value;
});
const increment = () => {
countStore.update((n) => n + 1);
};
</script>
<button on:click={increment}>Increment Count: {count}</button>
- PageB 组件
// PageB.svelte
<script>
// 这里不需要对 count 进行操作,只是展示路由切换
</script>
<p>This is PageB</p>
- 路由配置(以 svelte - routing 为例)
// main.js 或路由配置文件
import { Router, Route } from'svelte - routing';
import PageA from './PageA.svelte';
import PageB from './PageB.svelte';
const App = () => (
<Router>
<Route path="/pageA" component={PageA} />
<Route path="/pageB" component={PageB} />
</Router>
);
export default App;