后端多语言
1. 安装, 并注册
composer require overtrue/laravel-lang:~6.0
# 添加以下行到 bootstrap/app.php
$app->register(Overtrue\LaravelLang\TranslationServiceProvider::class);
2. 修改默认语言为简体中文
# vim config/app.php
'locale' => 'zh_CN',
3. 发布语言包
root@d92a8d4c6792:/var/www/ogenes/Genes-Admin# php artisan lang:publish zh_CN,zh_HK
published languages (no overwrite): ["zh_CN","zh_HK"].
root@d92a8d4c6792:/var/www/ogenes/Genes-Admin# ls -la lang/
total 100
drwxr-xr-x 8 root root 256 Aug 29 14:41 .
drwxr-xr-x 34 root root 1088 Aug 29 12:04 ..
drwxr-xr-x 6 root root 192 Aug 29 14:39 en
-rw-r--r-- 1 www-data www-data 677 Feb 15 2022 en.json
drwxr-xr-x 10 root root 320 Aug 29 14:37 zh_CN
-rw-r--r-- 1 root root 45610 Aug 29 14:37 zh_CN.json
drwxr-xr-x 10 root root 320 Aug 29 14:37 zh_HK
-rw-r--r-- 1 root root 45336 Aug 29 14:37 zh_HK.json
4. 测试
5. 自定义语言包
# vim lang/en/common.php
return [
'success' => 'success',
];
# vim lang/zh_CN/common.php
return [
'success' => '成功',
];
# vim lang/zh_HK/common.php
return [
'success' => '成功',
];
# vim app/Http/Controllers/User/AuthController.php
return response()->json([
'code' => 0,
'message' => trans('common.success'),
'data' => [
'token' => $token,
'user' => $user,
]
]);
前端多语言
1. 安装
npm install --save vue-i18n
2. 自定义语言包
#vim resources/src/i18n/langs/en/login.js
export const login = {
loginTitle: 'Login',
rememberMe: 'Remember me',
login: 'Login',
account: 'Account',
password: 'Password',
accountError: 'Please enter the correct account',
passwordError: 'The password can not be less than 6 digits',
}
#vim resources/src/i18n/langs/en/en.js
import enLocale from 'element-ui/lib/locale/lang/en'
import {login} from "./login";
const lang = {
loginForm: login,
...enLocale
};
export default lang;
#vim resources/src/i18n/langs/zh_CN/login.js
export const login = {
loginTitle: '请登录',
rememberMe: '记住我',
login: '登录',
account: '账号',
password: '密码',
accountError: '请输入正确的账号',
passwordError: '密码至少6位',
}
#vim resources/src/i18n/langs/zh_CN/zh_CN.js
import zhCNLocale from 'element-ui/lib/locale/lang/zh-CN'
import {login} from "./login";
const lang = {
loginForm: login,
...zhCNLocale
};
export default lang;
#vim resources/src/i18n/langs/zh_HK/login.js
export const login = {
loginTitle: '請登入',
rememberMe: '記住我',
login: '登入',
account: '帳號',
password: '密碼',
accountError: '請輸入正確的帳號',
passwordError: '密碼至少6比特',
}
#vim resources/src/i18n/langs/zh_HK/zh_HK.js
import zhHKLocale from 'element-ui/lib/locale/lang/zh-TW'
import {login} from "./login";
const lang = {
loginForm: login,
...zhHKLocale
};
export default lang;
#vim resources/src/i18n/langs/index.js
import en from './en/en';
import zh_CN from './zh_CN/zh_CN';
import zh_HK from './zh_HK/zh_HK';
export default {
en: en,
zh_CN: zh_CN,
zh_HK: zh_HK,
}
#vim resources/src/i18n/i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './langs'
Vue.use(VueI18n);
const i18n = new VueI18n({
//默认语言是中文简体
locale: localStorage.getItem('locale') || 'zh_CN',
messages,
silentTranslationWarn: true,
});
export default i18n
3. 配置
#vim resources/src/main.js
…………
import i18n from '@/i18n/i18n';
Vue.use(ElementUI, {
i18n: (key, value) => i18n.t(key, value)
})
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
i18n,
render: h => h(App)
})
4. 测试
#修改登录页面
#<h3 class="title">Login Form</h3>
<h3 class="title">{{ $t("loginForm.loginTitle") }}</h3>
#placeholder="Username"
:placeholder="$t('loginForm.account')"
#placeholder="Password"
:placeholder="$t('loginForm.password')"
#callback(new Error('Please enter the correct user name'))
callback(new Error(this.$t('loginForm.accountError')))
#callback(new Error('The password can not be less than 6 digits'))
callback(new Error(this.$t('loginForm.passwordError')))
切换语言
1. 前端切换
封装store模块
#vim resources/src/store/modules/app.js
import Cookies from 'js-cookie'
const state = {
sidebar: {
opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
withoutAnimation: false
},
device: 'desktop',
locale: localStorage.getItem('locale') || 'zh_CN',
}
const mutations = {
TOGGLE_SIDEBAR: state => {
state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false
if (state.sidebar.opened) {
Cookies.set('sidebarStatus', 1)
} else {
Cookies.set('sidebarStatus', 0)
}
},
CLOSE_SIDEBAR: (state, withoutAnimation) => {
Cookies.set('sidebarStatus', 0)
state.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation
},
TOGGLE_DEVICE: (state, device) => {
state.device = device
},
SET_LOCALE: (state, locale) => {
state.locale = locale
localStorage.setItem('locale', locale)
}
}
const actions = {
toggleSideBar({ commit }) {
commit('TOGGLE_SIDEBAR')
},
closeSideBar({ commit }, { withoutAnimation }) {
commit('CLOSE_SIDEBAR', withoutAnimation)
},
toggleDevice({ commit }, device) {
commit('TOGGLE_DEVICE', device)
},
setLocale({ commit }, locale) {
commit('SET_LOCALE', locale)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
#vim resources/src/store/getters.js
加入: locale: state => state.app.locale,
创建一个修改语言的组件, 放到导航栏
#vim resources/src/components/Language/index.vue
<template>
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
<svg-icon icon-class="language"/> {{ locale }}
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item
v-for="(lang, key) in languages"
:disabled="lang===locale"
:key="key"
:command="lang">
{{ lang }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</template>
<script>
export default {
name: "Language",
data() {
return {
languages: [
'en',
'zh_CN',
'zh_HK'
],
}
},
computed: {
locale() {
return this.$store.getters.locale;
}
},
methods: {
handleCommand(lang) {
this.$i18n.locale = lang
this.$store.dispatch('app/setLocale', lang)
this.$message.success('switch language success')
// 重新刷新页面更改语言
location.reload()
}
}
}
</script>
<style scoped>
</style>
#vim resources/src/layout/components/Navbar.vue
<template v-if="device!=='mobile'">
<languages id="header-language" class="right-menu-item"/>
</template>
import Languages from "@/components/Language";
将当前语言环境放进请求头
#vim resources/src/utils/request.js
service.interceptors.request.use(
config => {
// do something before request is sent
config.headers['locale'] = store.getters.locale;
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['Authorization'] = "Bearer " + store.getters.token
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
2. 后端切换
新建language中间件
root@d92a8d4c6792:/var/www/ogenes/Genes-Admin# php artisan make:middleware LanguageMiddleware
public function handle(Request $request, Closure $next)
{
$locale = $request->header('locale') ? : '';
App::setLocale($locale ? : 'zh_CN');
return $next($request);
}
引入中间件
#vim app/Http/Kernel.php
protected $routeMiddleware = [
…………
'auth.jwt' => Authenticate::class,
'language' => LanguageMiddleware::class,
];
生效
#vim routes/api.php
Route::middleware(['language'])->group(function () {
Route::post('/user/login', [AuthController::class, 'login']);
Route::post('/user/logout', [AuthController::class, 'logout']);
Route::middleware(['auth.jwt'])->group(function () {
Route::post('/user/userinfo', [AuthController::class, 'userinfo'])->name('Userinfo');
});
});