安装
yarn add @nuxtjs/i18n # yarn
npm i @nuxtjs/i18n # npm
配置
nuxt.config.js
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'@nuxtjs/axios',
['@nuxtjs/i18n', {
locales: ['en', 'zh'],// 语种
defaultLocale: 'zh', // 默认语种
vueI18n: {
fallbackLocale: 'zh', // 回退策略
messages: {
en: {home: 'Home'},
zh: {home: '首页'}
}
}
}]
],
使用
在 vue 文件中使用
<template>
<h1>{{ $t('home') }}</h1>
<!-- 切换语言 -->
<nuxt-link :to="switchLocalePath('en')">
en
</nuxt-link>
<nuxt-link :to="switchLocalePath('zh')">
zh
</nuxt-link>
<!-- 路由跳转 -->
<nuxt-link :to="localePath('/home')">
{{ $t('home') }}
</nuxt-link>
</template>
切换不是默认语言的时候,路由地址中会带有切换的语言信息。因此要保证切换的语言在切换路由的时候不会变,就需要使用 localePath 方法修改路由。
this.$router.push({path: this.localePath('/test')})
获取实例
this.$i18n