解决vue i18n 项目中 title 双英 切换问题

主要问题点在于 router 中无法用 this.$t('xxx.xx') 方法来进行翻译,会报错 this.$t is not a function 。而在main.js中可以使用,所以就做了一下处理:

main.js文件:

const i18n = new Vue18n({
  locale: lan,
  messages: {
    zh: require("./assets/i18n/zh"),
    en: require("./assets/i18n/en")
  },
  silentTranslationWarn: true
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = `${i18n.t('meta.'+to.meta.title)} - ${i18n.t('meta.base')}`
  }
  next()
})

navbar.vue中点击切换语言:

    changeLan(type) {
        this.$i18n.locale = type;
        document.title = `${i18n.t('meta.'+this.$route.meta.title)} - ${i18n.t('meta.base')}`
    }

router/index.js中(关键点是里面设置的title要和i18n配置中的相对应):

export default new Router({
  mode: 'history',
  routes: [
    { path: '/XX', name: 'XX',meta: { title: 'A' },……},
    { path: '/XX', name: 'XX',meta: { title: 'B' }, …… },
  ]
})

en.js/zh.js配置:

module.exports = { 
 meta:{base:'XXX',A:'XXX',B:'X',E:'XX'}
};

这样下来点击切换页面title也同时改变,爽歪歪,哈哈

当然目前代码有点冗余,两处改变document.title的方法都一样,提公用下,assets/js中新建title.js:

export function getPageTitle(i18n,key) {
  const hasKey = i18n.te(`meta.${key}`)
  const title = i18n.t(`meta.base`)
  if (hasKey) {
    const pageName = i18n.t(`meta.${key}`)
    return `${pageName} - ${title}`
  }
  return `${title}`
}

这个方法是参考 vue-element-admin i18n分支里的方法,比较完善一些。

分别在main.js和navbar.vue中引入:

import { getPageTitle } from './assets/js/title';

import { getPageTitle } from '../../assets/js/title';

main.js中:

const i18n = new Vue18n({
  locale: lan,
  messages: {
    zh: require("./assets/i18n/zh"),
    en: require("./assets/i18n/en")
  },
  silentTranslationWarn: true
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = getPageTitle(i18n,to.meta.title)
  }
  next()
})

navbar.vue中:

    changeLan(type) {
      this.$i18n.locale = type;
      document.title = getPageTitle(this.$i18n,this.$route.meta.title)
    }

然后OK。

另附上Vue i18n 官方API:

$te

  • 参数:

    • {Path} key:必填
    • {Locale} locale:可选
  • 返回值:boolean

检查 key 是否存在。在 Vue 实例中,如果未指定组件语言环境信息,则使用全局语言环境信息。如果指定了 locale,则使用 locale 的语言环境。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值