基础实现
1. 建一个文件夹,如图:
zh-cn.json
{
title: "标题"
}
2. 建一个js utils,写一个方法,去处理多语言
/**
* 解析字符串为字典格式
* @param {string} [query] url字符串,不传的时候默认会取当前页面的url
* @returns {object} url上的参数对象,包含了url上的正常参数与hash后的参数
*/
function resolveQuery (query) {
let search = ''
let hash = ''
let hashSearch
if (query) {
let getHash = pickStringByIndentifier(query, '#')
hash = getHash.result
let getSearch = pickStringByIndentifier(getHash.rest, '?')
search = getSearch.result
} else {
if (window && window.location) {
search = window.location.search
hash = window.location.hash
}
}
hashSearch = pickStringByIndentifier(hash, '?').result
let searchObj = resolveSearch(search)
let hashSearchObj = resolveSearch(hashSearch)
return Object.assign({}, searchObj, hashSearchObj)
}
const { lang } = resolveQuery()
const LANG_TYPES = [
'zh-cn',
'en-us'
]
function langData() {
let langVal = lang || 'zh-cn'
if (langVal) {
langVal = langVal.toLocaleLowerCase()
}
if (!LANG_TYPES.includes(langVal)) {
langVal = 'zh-cn'
}
return require(`../langs/${langVal}.json`)
}
export {
langData
}
3. 引用
<template>
<div>{{ langText.title }}</div>
</template>
import { langData } from 'utils'
const langText = langData()
export default {
data() {
return {
langText
}
}
}