ChuChencheng / note

菜鸡零碎知识笔记
Creative Commons Zero v1.0 Universal
3 stars 0 forks source link

在 vitepress 使用 @vue/repl 报错 Failed to load code from URL. #52

Open ChuChencheng opened 2 months ago

ChuChencheng commented 2 months ago

背景

在 vitepress 文档中链接到运行 @vue/repl 的页面,弹了个 Alert 显示 Failed to load code from URL. 无法正常打开代码示例

问题分析

在链接生成后,使用了 vitepress 的 withBase 来处理链接:

<a :href="withBase(`/playground${serializedCode}`)" target="_blank" rel="noreferrer noopener">{{ text || i18n.openInPlayground }}</a>

serializedCode@vue/repl store.serialize() 生成的字符串

具体查看 vitepress withBase 调用的 joinPath 源码

/**
 * Join two paths by resolving the slash collision.
 */
export function joinPath(base: string, path: string) {
  return `${base}${path}`.replace(/\/+/g, '/')
}

可以看到这个函数对整个参数进行了一次 replace

由于 @vue/repl 生成的是 base64 编码的字符串,其中也包含 / 字符,因此经过 withBase 处理之后,就无法进行 base64 解码了

解决

@vue/repl 生成的字符串放在 withBase 之外可解决

<a :href="withBase('/playground') + serializedCode" target="_blank" rel="noreferrer noopener">{{ text || i18n.openInPlayground }}</a>