vue-i18n@11,读取json文件中保存的json对象字符串报错处理

13 阅读1分钟

事情起因

最近我打算更新下简历,但是吧,在线的简历它不能在线编辑,因为它只是一个静态的页面。于是乎,问了下AI,有关无服务器的方案。推荐我使用github的Api。那么对于项目经验这种数组类型的,思来想去,只能保存为json的字符串,然后再挂载到json树上。那么问题就来了。

解决方案

export const messageCompiler = (message, { locale, key, onError }) => {
  if (typeof message === "string") {
    /**
     * You can tune your message compiler performance more with your cache strategy or also memoization at here
     */
    return () => {
      return message;
    };
  } else {
    /**
     * for AST.
     * If you would like to support it,
     * You need to transform locale messages such as `json`, `yaml`, etc. with the bundle plugin.
     */
    onError && onError(new Error("not support for AST"));
    return () => key;
  }
};
// 国际化
const i18n = createI18n({
  legacy: false,
  locale: "zh",
  fallbackLocale: "en",
  messages: {},
  compiler: false,
  messageCompiler,
});

代码说明

vue-i18n@11支持很多特性,对于字符串中的特殊字符比如@、{},都会进行匹配,因此会报错,这里我们使用自定义消息解析器,不需要对任何特殊字符校验,报错就解决了。