vue + elementUI 添加多语种切换功能

1. 准备3个js文件

1.1 en.js、zh.js 用于替换语言字段

# en.js
export default {
    register: 'register',
    forgetpassword: 'ForgetPassword?',
    Login: 'Login',
}

# zh.js
export default {
    register: '注册',
    forgetpassword: '忘记密码?',
    Login: '登录',
}

1.2 i18n.js 用于配置i18n

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enLocalefrom from 'element-ui/lib/locale/lang/en'
import zhLocalefrom from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from '../lang/en'  # 引入本地en.js
import zhLocale from '../lang/zh'  # 引入本地zh.js
import locale from 'element-ui/lib/locale'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: localStorage.getItem('locale') || 'zh',
  messages: {
    'en': {
      ...enLocale,
      ...enLocalefrom
    },
    'zh': {
      ...zhLocale,
      ...zhLocalefrom
    }
  }
})

locale.i18n((key, value) => i18n.t(key, value))

export default i18n  # 务必export i18n

1.3 main.js引入i18n

import i18n from './i18n/i18n'  # 引入本地配置的i18n.js‘

new Vue({
  el: '#app',
  router,
  store,
  i18n,  # Vue中引入
  render: h => h(App),
})

2. 使用多语言字段

2.1 html中使用

<el-dropdown-item>{{ $t('Login') }}</el-dropdown-item>
<el-input
  :placeholder="$t('Login')"  # en.js、zh.js中导出的变量
/>

2.2 js中使用

import i18n from '/src/i18n/i18n'

message: i18n.t('Login')

3. 切换语言

# html
<el-dropdown
    class="right-menu-item"
  trigger="click"
>
  <div>
    <svg-icon
      icon-class="language"
      class-name="language-icon"
    />
  </div>
  <el-dropdown-menu slot="dropdown">
    <el-dropdown-item
      :disabled="$i18n.locale == 'zh'"
      @click.native="toggleLang('zh')"
    >中文</el-dropdown-item>
    <el-dropdown-item
      :disabled="$i18n.locale == 'en'"
      @click.native="toggleLang('en')"
    >English</el-dropdown-item>
  </el-dropdown-menu>
</el-dropdown>

# js
toggleLang(lang) {
  if (lang == "zh") {
    localStorage.setItem("locale", "zh");
    this.$i18n.locale = localStorage.getItem("locale");
    this.$message({
      message: "切换为中文",
      type: "success",
    });
  } else if (lang == "en") {
    localStorage.setItem("locale", "en");
    this.$i18n.locale = localStorage.getItem("locale");
    this.$message({
      message: "Switch to English",
      type: "success",
    });
  }
  location.reload();  # 如有字段没有成功更改,可添加刷新页面步骤
},
posted @ 2022-01-29 16:35  Ravenna  阅读(380)  评论(0编辑  收藏  举报