nuxt.config.js的plugins中
'~plugins/lang/index.js',
plugins/lang/index.js
import Vue from "vue";
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
let cookieFun = {set: function(key, val, time) { //设置cookie方法var date = new Date(); //获取当前时间var expiresDays = time; //将date设置为n天以后的时间date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000); //格式化为cookie识别的时间document.cookie = key + "=" + val + ";expires=" + date.toGMTString(); //设置cookie},get: function(key) { //获取cookie方法/*获取cookie参数*/var getCookie = document.cookie.replace(/[ ]/g, ""); //获取cookie,并且将获得的cookie格式化,去掉空格字符var arrCookie = getCookie.split(";") //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中var tips; //声明变量tipsfor (var i = 0; i < arrCookie.length; i++) { //使用for循环查找cookie中的tips变量var arr = arrCookie[i].split("="); //将单条cookie用"等号"为标识,将单条cookie保存为arr数组if (key == arr[0]) { //匹配变量名称,其中arr[0]是指的cookie名称,如果该条变量为tips则执行判断语句中的赋值操作tips = arr[1]; //将cookie的值赋给变量tipsbreak; //终止for循环遍历}}return tips;}
}
export default (context) => {let cookieObj = false;if (context.req && context.req.headers.cookie) {cookieObj = {};let cookiestr = context.req.headers.cookie;cookiestr.split(';').map((item) => {let k = item.split('=')[0].replace(' ', '')let v = item.split('=')[1]let obj = {[k]: v}cookieObj[k] = vreturn obj});}let lang = 'en'; // 无数据默认语言 const languages = { // (西班牙语) 法语 Fran?ais'en': "English", // 英语"es": "Espa?ol", // 西班牙语"fr": "Fran?ais", // 法语"de": "Deutsch", // 德语"pt": "Português" // 葡萄牙语}let langs = Object.keys(languages); // 支持的所有语言简写const urlhref = context.route.fullPath.toString(); // 获取地址栏数据const urllen = urlhref.indexOf("?");let urllang = '';let locallang = '';if (urllen !== -1) {let urldata = urlhref.split('?')[1].split('&');urldata.forEach((item) => {if (item && item.includes('=')) {const itemData = item.split('=');if (itemData[0] === 'lang') {urllang = itemData[1]}}})}if (urllang && langs.includes(urllang)) { // 有url语言信息if (langs.includes(urllang)) {lang = urllang}} else { // 读缓存try {if (context.req && cookieObj) { // 服务器端locallang = cookieObj['lang']} else {locallang = cookieFun.get('lang')}if (locallang && langs.includes(locallang)) {lang = locallang}} catch (error) {}}try {if (!context.req && langs.includes(lang)) { // 客户端设置浏览器cookiecookieFun.set('lang', lang, 360);localStorage.setItem('lang', lang);document.body.setAttribute('lang', lang);document.getElementById('document-html').setAttribute('class', lang)}} catch (error) {}const messages = {[lang]: require('./' + lang + "/index.json") // 动态加载语言包}const i18n = new VueI18n({locale: lang, // 选择语言messages, // 语言文件})i18n.languages = languages;return i18n;
}