nuxt 多语言配置,nuxt + @nuxt/vuetify + @nuxt/i18n

直接上配置

vue.config.js 配置片段

export default {
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    { src: '~/plugins/i18n.js' } //多语言配置文件
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    '@nuxtjs/i18n',
  ],
  i18n: {
    locales: [
      {name: 'English', code: 'en', iso: 'en-US', file: 'en.js'},
      {name: '简体中文', code: 'zh', iso: 'zh-cn', file: 'zh.js'},
    ],
    lazy: true,
    langDir: '~/lang/',
    defaultLocale: 'en',
    baseUrl: 'http://192.168.1.7:3002'
  },
  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/vuetify
    ['@nuxtjs/vuetify', {
      customVariables: ['~/assets/css/variables.scss'],
      defaultAssets: {
        font: false,
        icons: 'mdi'
      },
      treeShake: true,
    }]
  ],

  vuetify : {
    optionsPath : '~/plugins/vuetify.options.js'
  },
}

项目目录截图重要的文件我框起来了

 vuetify.options.js 文件内容

// vuetify.options.js
export default function ({app}) {
  return {
    lang: {
      t: (key, ...params) => app.i18n.t(key, params)
    }
  }
}

i18n.js 文件内容    这个文件无关紧要贴出来下~~

export default function ({ app }) {
  // onBeforeLanguageSwitch called right before setting a new locale
  app.i18n.onBeforeLanguageSwitch = (oldLocale, newLocale, isInitialSetup, context) => {
    console.log(oldLocale, newLocale, isInitialSetup)
  }
  // onLanguageSwitched called right after a new locale has been set
  app.i18n.onLanguageSwitched = (oldLocale, newLocale) => {
    console.log(oldLocale, newLocale)
  }
}

重要的来了

en.js

import en from 'vuetify/lib/locale/en' //引入vuetify语言包
export default {
  name:'xiaoyuren',
  home:'home',
  about:'about',
  $vuetify: en, //照着这个来
};

zh.js

import zhHans from 'vuetify/lib/locale/zh-Hans'
export default {
  name:'小鱼人',
  home:'首页',
  about:'关于我们',
  $vuetify: zhHans,
}

 照着来应该没问题了,结束!!!!

最后上个完整配置参考下得了 nuxt.config.js

import colors from 'vuetify/es5/util/colors'
import path from 'path'
import fs from 'fs'

const prodPlugins = []
if (process.env.NODE_ENV === 'production') {
  prodPlugins.push('transform-remove-console')
}

export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    __dangerouslyDisableSanitizers: ['script', 'noscript'],//不转义script标签的内容,用于结构化数据
    titleTemplate: '%s - nuxt_demo',
    title: 'nuxt_demo',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      {charset: 'utf-8'},
      {'http-equiv': "X-UA-Compatible", content: "IE=edge"},
      {name: "renderer", content: "webkit"},
      {name: 'viewport', content: 'width=device-width, initial-scale=1'},
      {hid: 'description', name: 'description', content: ''},
      {hid: "keywords", name: "keywords", content: ""},
      {name: 'format-detection', content: 'telephone=no'}
    ],
    link: [
      {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'},
      {
        rel: "preload",
        href:
          "https://sticker-static.oss-us-west-1.aliyuncs.com/static/font/calibri-regular.woff",
        as: "font",
        type: "font/woff",
        crossorigin: "anonymous"
      }
    ],
    script: [
      // {
      //   src: "/js/lib-flexible.js", // 淘宝手机端适配解决方案
      //   body: true
      // },
      // {
      //   src: "/js/chat.js", // 聊天插件
      //   body: true,
      //   async: true,
      //   defer: true
      // }
    ],
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
    '~/assets/css/main.scss',
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    {src: '~/plugins/axios.js'},
    {src: '~/plugins/filter.js'},
    {src: '~/plugins/globalBus.js'},
    { src: '~/plugins/i18n.js' }
  ],

  server: {
    port: 3002, // default: 3000
    host: '0.0.0.0', // default: localhost,
    timing: false,
    // https: {
    //   key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
    //   cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
    // }
  },

  render: {
    resourceHints: false, //禁用预加载
    asyncScripts: true
  },

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxtjs/style-resources',
    '@nuxtjs/i18n',
  ],
  i18n: {
    locales: [
      {name: 'English', code: 'en', iso: 'en-US', file: 'en.js'},
      {name: '简体中文', code: 'zh', iso: 'zh-cn', file: 'zh.js'},
    ],
    lazy: true,
    langDir: '~/lang/',
    defaultLocale: 'en',
    baseUrl: 'http://192.168.1.7:3002'
  },

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/vuetify
    ['@nuxtjs/vuetify', {
      customVariables: ['~/assets/css/variables.scss'],
      defaultAssets: {
        font: false,
        icons: 'mdi'
      },
      treeShake: true,
    }]
  ],

  vuetify : {
    optionsPath : '~/plugins/vuetify.options.js'
  },

  styleResources: {
    //全局scss变量
    sass: ['./assets/css/variables.scss']
  },

  router: {
    middleware: []
  },

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {},

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    analyze: true,
    postcss: {
      plugins: {
        cssnano: {
          preset: [
            "default",
            {
              calc: false
            }
          ]
        }
      }
    },
    babel: {
      plugins: [
        ...prodPlugins //打包移除console
      ],
    },
    //分割vendor.app.js文件(打包优化)
    optimization: {
      minimize:true,
      splitChunks: {
        minSize: 1000000,
        maxSize: 2500000,
        cacheGroups: {
          // //缓存组,将所有加载模块放在缓存里面一起分割打包
          vendors: {
            chunks: "initial",
            // 提升权重,先抽离第三方模块,再抽离公共模块,要不然执行抽离公共模块就截止不会往下执行
            priority: 100,
            // 文件最小字节
            minSize: 10240,
            test: /[\\/]node_modules[\\/]/
          },
          common: {
            chunks: "all",
            priority: 10,
            // 文件最小字节
            minSize: 10240,
            // 引用次数
            minChunks: 2,
            //模块嵌套引入时,判断是否复用已经被打包的模块
            reuseExistingChunk: true
          }
        }
      }
    }
  }
}

package.json文件

{
  "name": "nuxt + @nuxt/vuetify + @nuxtjs/i18n",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/i18n": "^7.0.3",
    "@nuxtjs/vuetify": "^1.12.1",
    "core-js": "^3.15.1",
    "nuxt": "^2.15.7",
    "vuetify": "^2.5.5"
  },
  "devDependencies": {
    "@nuxt/types": "^2.15.8",
    "@nuxtjs/style-resources": "^1.2.1",
    "babel-plugin-transform-remove-console": "^6.9.4"
  }
}

再看看怎么使用吧 default.vue文件

<template>
  <v-app>
    <v-system-bar
      height="40"
      app
      dark
      color="primary"
    >
      <span>{{ $t('name') }}</span>
      <v-spacer></v-spacer>
      <v-menu offset-y open-on-hover>
        <template v-slot:activator="{ on, attrs }">
          <v-btn text v-bind="attrs" v-on="on">
            <v-icon>
              mdi-translate
            </v-icon>
            <v-icon>
              mdi-chevron-down
            </v-icon>
          </v-btn>
        </template>
        <v-list>
          <v-list-item
            v-for="locale in availableLocales"
            :key="locale.name"
            @click="changeLang(locale)"
          >
            <v-list-item-title>{{ locale.name }}</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-system-bar>
    <v-app-bar app>
      <v-app-bar-nav-icon @click="drawer = true"></v-app-bar-nav-icon>
      <v-toolbar-title>Collapsing Bar</v-toolbar-title>
      <ul class="d-flex justify-space-between align-center">
        <li class="mx-2">
          <nuxt-link :to="localePath('index')">{{ $t('home') }}</nuxt-link>
        </li>
        <li class="mx-2">
          <nuxt-link :to="localePath('about-us')">{{ $t('about') }}</nuxt-link>
        </li>
      </ul>
    </v-app-bar>
    <v-navigation-drawer absolute temporary v-model="drawer">
      <v-list-item>
        <v-list-item-content>
          <v-list-item-title class="text-h6">
            Application
          </v-list-item-title>
          <v-list-item-subtitle>
            subtext
          </v-list-item-subtitle>
        </v-list-item-content>
      </v-list-item>

      <v-divider></v-divider>

      <v-list
        dense
        nav
      >
        <v-list-item
          v-for="item in items"
          :key="item.title"
          link
        >
          <v-list-item-icon>
            <v-icon>{{ item.icon }}</v-icon>
          </v-list-item-icon>

          <v-list-item-content>
            <v-list-item-title>{{ item.title }}</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>
    <!-- 根据应用组件来调整你的内容 -->
    <v-main>

      <!-- 给应用提供合适的间距 -->
      <v-container fluid>

        <nuxt></nuxt>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>

export default {
  head () {
    const i18nHead = this.$nuxtI18nHead({ addSeoAttributes: true })
    return {
      htmlAttrs: {
        ...i18nHead.htmlAttrs
      },
    }
  },
  data() {
    return {
      items: [
        {title: 'Dashboard', icon: 'mdi-view-dashboard'},
        {title: 'Photos', icon: 'mdi-image'},
        {title: 'About', icon: 'mdi-help-box'},
      ],
      right: null,
      drawer: false,
      value: 'recent'
    }
  },
  computed: {
    availableLocales() {
      return this.$i18n.locales.filter(i => i.code)
    }
  },
  methods: {
    //切换语言
    changeLang(locale) {
      this.$i18n.setLocale(locale.code)
    }
  },
  mounted() {

  }
}
</script>

再来两张效果图

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值