在 Vue.js 中实现语言切换,可以使用国际化插件 'vue-i18n'。

首先,安装 'vue-i18n' 插件:

npm install vue-i18n --save

然后,在项目的主文件(一般是 main.js)中导入并使用 'vue-i18n' 插件:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import App from './App.vue'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'zh', // 默认语言为中文
  messages: {
    zh: require('./locales/zh.json'), // 导入中文语言包
    en: require('./locales/en.json')  // 导入英文语言包
  }
})

new Vue({
  el: '#app',
  i18n,
  render: h => h(App)
})

接下来,在项目中创建 'locales' 文件夹,并在其中创建 'zh.json' 和 'en.json' 两个语言包文件,分别存放中文和英文的翻译内容。例如,'zh.json' 文件内容如下:

{
  'hello': '你好',
  'world': '世界'
}

'en.json' 文件内容如下:

{
  'hello': 'Hello',
  'world': 'World'
}

在需要进行语言切换的组件中,可以使用 $t 函数来获取对应语言的翻译内容。例如,在 'App.vue' 组件中,可以这样使用:

<template>
  <div id='app'>
    <p>{{ $t('hello') }}</p>
    <p>{{ $t('world') }}</p>
    <button @click='changeLanguage'>切换语言</button>
  </div>
</template>

<script>
export default {
  methods: {
    changeLanguage() {
      if (this.$i18n.locale === 'zh') {
        this.$i18n.locale = 'en'
      } else {
        this.$i18n.locale = 'zh'
      }
    }
  }
}
</script>

这样,点击切换语言按钮时,页面中的汉字会变为英文,再次点击则会切换回中文。

Vue.js 国际化实现语言切换 - 简易教程

原文地址: https://www.cveoy.top/t/topic/pkmI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录