【问题标题】:Svelte components store - load state into - from URL hash parametersSvelte 组件存储 - 将状态加载到 - 从 URL 哈希参数
【发布时间】:2019-12-03 17:13:09
【问题描述】:

如果我们有一个S单个P年龄一个使用Svelte构建的应用程序,其中包含一堆组件和我们保留当前应用程序状态的商店,是否有推荐的方法将商店状态更改存储到当前 URL 的 # 哈希部分,并能够从完整重新加载相同的状态网址?

可以通过location.search()解析当前URL手动完成。

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

一些问题:

  • 何时从 URL 加载状态? App init 条目是什么 点?
  • 何时将状态从商店存储到 URL?有没有通用的 如何做到这一点?

【问题讨论】:

  • 从未使用过它,但看起来svelte-spa-router 提供了开箱即用的查询字符串支持。
  • @skyboyer 谢谢,没看过。这对我来说是全新的,所以当你学习时,你倾向于重新实现轮子。
  • 你能附上你的答案吗?其他人将如何通过搜索登陆这里将不会检查 cmets :(

标签: javascript svelte svelte-3


【解决方案1】:

编辑:

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


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

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);
}

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

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2014-08-17
    • 2012-09-03
    • 2012-05-28
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多