目标==在项目中常有后台返回的字段是英文,没有引入国际化包 i18n 时翻译将返回的字段翻译为中文
项目使用了Vue2版本开发 想到的方法是 用 拦截器(filter)将后台返回的字段翻译成中文
在组件页面中
<template>
... //页面展示
{{ item | formatItem }} //item 为动态渲染的后台字段 ; formatItem为我们自己定义的拦截器
</template>
在自定义拦截器的文件中
一开始想到的笨办法是 使用 switch 语句 根据传入的值 遍历 case 再将翻译后的值 return 出去
export function formatItem(value){
if (value === null || value === undefined || value === "") {
return "";
}
swicth(value){
case "type1":
return "方式1";
case "type2":
return "方式2";
case "type3":
return "方式3";
case "type4":
return "方式4";
case "type5":
return "方式5";
default:
return "";
}//使用switch可以完成需求 但是还有更优解
}
将后台返回字段和翻译后的字段用 json 串存起来 在取用的时候只需要调用 json串[key] 就可以获取翻译后的值
const fieldName = {
"type1":"方式1",
"type2":"方式2",
"type3":"方式3",
"type4":"方式4",
"type5":"方式5",
}
export function formatItem(value){
if (value === null || value === undefined || value === "") {
return "";
}
return fieldName[value]// 代码看起来更简洁
}