【发布时间】:2019-08-18 05:28:48
【问题描述】:
我在通用模式下开发了项目 Nuxt.js 并使用 i18n 本地化工作正常,但现在我想更改为 spa 模式但 i18n 不会更改语言。
这是代码。
文件:nuxt.config.js
import colors from "vuetify/es5/util/colors";
export default {
mode: "spa",
/*
** Headers of the page
*/
head: {
meta: [
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{
hid: "description",
name: "description",
content: process.env.npm_package_description || ""
}
],
link: [
{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" },
{
rel: "stylesheet",
href:
"https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"
}
]
},
/*
** Customize the progress-bar color
*/
loading: { color: "#fff" },
/*
** Global CSS
*/
css: ["~/assets/main.css"],
router: {
middleware: "i18n"
},
/*
** Plugins to load before mounting the App
*/
plugins: [
"~/plugins/mdi-font.js",
"~/plugins/i18n.js",
"~/plugins/axios.js",
{ src: "~/plugins/flag.js", ssr: false }
],
/*
** Nuxt.js modules
*/
modules: [
"@nuxtjs/vuetify",
// Doc: https://axios.nuxtjs.org/usage
"@nuxtjs/axios"
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {},
/*
** vuetify module configuration
** https://github.com/nuxt-community/vuetify-module
*/
vuetify: {
theme: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {}
}
};
文件:middleware/i18n.js
export default function ({ isHMR, app, store, route, params, req, error, redirect }) {
if (isHMR) { // ignore if called from hot module replacement
return;
}
if (req) {
if (route.name) {
let locale = null;
// check if the locale cookie is set
if (req.headers.cookie) {
const cookies = req.headers.cookie.split('; ').map(stringCookie => stringCookie.split('='));
const cookie = cookies.find(cookie => cookie[0] === 'locale');
if (cookie) {
locale = cookie[1];
}
}
// if the locale cookie is not set, fallback to accept-language header
if (!locale) {
locale = req.headers['accept-language'].split(',')[0].toLocaleLowerCase().substring(0, 2);
}
store.commit('SET_LANG', locale);
app.i18n.locale = store.state.locale;
}
}
};
store/index.js
export const state = () => ({
locales: [
{
code: 'en',
name: 'EN',
flag: 'us'
},
{
code: 'fa',
name: 'FA',
flag: 'af'
},
{
code: 'pa',
name: 'PA',
flag: 'af'
}
],
locale: 'en'
});
export const mutations = {
SET_LANG(state, locale) {
if (state.locales.find(el => el.code === locale)) {
state.locale = locale
}
}
};
和licalize文件在locales/fa.json and en.json
【问题讨论】:
标签: javascript single-page-application nuxt.js vue-i18n