Vic*_*tor 3 javascript internationalization vue.js vue-i18n
我有一个locale.js文件,负责定义用户区域设置。这里是:
import store from '@/vuex/index'
let locale
const defaultLocale = 'en_US'
if (store.getters['auth/authenticated']) {
locale = store.getters['auth/currentUser'].locale || defaultLocale
} else {
if (localStorage.getItem('locale')) {
locale = localStorage.getItem('locale')
} else {
locale = defaultLocale
}
}
export default locale
Run Code Online (Sandbox Code Playgroud)
另外,我还有一个i18n.js文件,负责制作i18n我在初始化应用程序时使用的实例。
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from '@/services/locale'
Vue.use(VueI18n)
const fallbackLocale = 'en_US'
let i18n = new VueI18n({
locale,
fallbackLocale,
})
i18n.setLocaleMessage('ru_RU', require('@/lang/ru_RU.json'))
i18n.setLocaleMessage('en_US', require('@/lang/en_US.json'))
export { i18n }
Run Code Online (Sandbox Code Playgroud)
现在,我认为以区域设置为前缀的URL会更方便 /en/profile或)/ru/profile。这样,我可以与已经设置的语言环境共享一个链接。
不确定如何执行此操作。将所有路由设置为子路径和放置路径/:locale?并不方便,因为路由器尚未初始化(我通过i18nrouter根应用程序实例时,同时和实例)。
我怎样才能做到这一点,最好的方法是什么?
你可以实现路由器
routes: [{
path: '/:lang',
children: [
{
path: 'home'
component: Home
},
{
path: 'about',
component: About
},
{
path: 'contactus',
component: ContactUs
}
]
}]
Run Code Online (Sandbox Code Playgroud)
并设置locale在beforeEach挂钩中
// use beforeEach route guard to set the language
router.beforeEach((to, from, next) => {
// use the language from the routing param or default language
let language = to.params.lang;
if (!language) {
language = 'en';
}
// set the current language for vuex-i18n. note that translation data
// for the language might need to be loaded first
Vue.i18n.set(language);
next();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6404 次 |
| 最近记录: |