编辑:
svelte-spa-router似乎提供了开箱即用的查询字符串支持。
我最终使用URLSearchParams和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);
}
它比这更棘手,因为您需要注意默认配置并从序列化配置中删除与默认值相同的值。即使此时尚未修改配置,也会在加载配置时最初调用订阅。