vue i18n 如何在非 template 中渲染?

发布于 2022-09-12 23:07:05 字数 1420 浏览 19 评论 0

main.js

import Vue from 'vue'
import App from '@/App.vue'
import VueI18n from 'vue-i18n'
import router from '@/router'
import store from '@/store'
import lang from '@/utils/lang'
...略

Vue.use(VueI18n)
Vue.config.productionTip = false

const i18n = new VueI18n({
  locale: 'cn',
  messages: lang, 
})

new Vue({
  i18n,
  router,
  store,
  render: h => h(App),
}).$mount('#app')

lang.js

const lang = {
    cn: {
        setting: {
            webTitle: '工作室',
        }
    },
    en: {
        setting: {
            webTitle: 'Studio',
        }
    },
}

export default lang

@/router/index

import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/components/Layout'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: () => import('@/views/index'),
      },
      ...略
    ],
  },
]

const router = new VueRouter({
  mode: 'history',
  base: '/',
  routes
})

router.beforeEach((to, from, next) => {
  document.title = `${$t('setting.webTitle')}${to.meta.title ? ` - ${to.meta.title}` : ''}`
  next()
})

export default router

假設要在 router.beforeEach 中也使用 $t
我試了下 ${$t('setting.webTitle')} 它都是會說找不到 $t is not defined
還是說擺放的順序有問題?
但是在 template 中可以正常使用 $t

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤城病女 2022-09-19 23:07:06

$t实际上是this.$t, template 中 $t 是全局注入的,而在 beforeEach 钩子中,无法访问组件的 this,参考 导航守卫, 改成 beforeRouteUpdate 试下,当然也可以在 beforeEach 的 next 回调中 使用, eg:

router.beforeEach((to, from, next) => {
  next(vm=>{
    document.title = `${vm.$t('setting.webTitle')}${to.meta.title ? ` - ${to.meta.title}` : ''}`
  })
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文