Svelte 组件从 URL 哈希参数中存储 - 加载状态

Svelte components store - load state into - from URL hash parameters

如果我们有一个 Single Page A应用 Svelte 有一堆组件和我们保存当前应用程序状态的商店,是否有推荐的方法将商店状态更改存储到当前 [=] 的 # 哈希部分37=] 并且能够从完整的状态重新加载相同的状态 URL?

可以手动解析当前的URL和location.search()

参数的存储可以用location.search("key", "value")来完成。

一些问题:

编辑:

svelte-spa-router 似乎提供开箱即用的查询字符串支持。


我最终使用 URLSearchParams and polyfill 编写函数来序列化和反序列化保存在存储中的配置对象:

import 'url-search-params-polyfill';

export function deserializeConfig(serializedConfig, resultConfig) {
  let hashParams = new URLSearchParams(serializedConfig);
  for (const hashParameterAndValue of hashParams.entries()) {
    const key = hashParameterAndValue[0];
    const value = hashParameterAndValue[1];

    const decodedKey = decodeUrlParameterKey(key);
    const decodedValue = decodeUrlParameterValue(value);

    resultConfig[decodedKey] = decodedValue;
  }


export function serializeConfig(config) {
  const hashParams = new URLSearchParams("");

  for (const key in config) {
    const value = config[key];
    const encodedValue = encodeParameterValue(value);
    const encodedKey = encodeParameterKey(key);;
    hashParams.set(encodedKey, encodedValue);
  }

  const serializedConfig = hashParams.toString();
  return serializedConfig;
}

使用它来序列化/反序列化来自 URL 散列的状态:

在 main.js:

import { configFromStore } from "./stores.js";

let config = {};

// when config from store changes
configFromStore.subscribe(updatedConfig => {
    config = updatedConfig;

   // check if the config was really modified and does not match the default
   if (!isEquivalent(updatedConfig, defaultConfig)) {
     // update URL hash after store value has been changed
     const serializedConfig = serializeConfig(updatedConfig);
     window.location.hash = "#" + serializedConfig;
   }
}

// on main app start, parse state from URL hash
const hash = window.location.hash;
if (hash && hash.length > 1) {
    const serializedConfig = hash.substr(1);
    deserializeConfig(serializedConfig, config);
    configFromStore.set(config);
}

它比这更棘手一些,因为您需要注意默认配置并从序列化配置中删除与默认配置相同的值。 此外,即使此时尚未修改配置,也会在加载配置时最初调用订阅。