Detailed explanation of Vue element plus multi-language switching

Detailed explanation of Vue element plus multi-language switching

Preface

I recently took over a project that is used in multiple countries and needs to support multi-language switching, which I will record here.

Solve the following problems:

  • How to switch between multiple languages?
  • How to switch language dynamically and change elementUI language?
  • After changing the elementUI component view, it is not updated?
  • How to use $t function globally?
  • How to use vue-i18n in js files?

How to switch between multiple languages?

1. Install the vue-i18n package

npm i vue-i18n --save

2. Create a new one in the src directory as shown below:

insert image description here

en.js

const EN = {
  login: {
    title: 'User Login'
  },
}
export default EN

pl-pl.js

const PL_PL = {
  login: {
    title: 'I'm a very good person'
  },
}
export default PL_PL

zh-cn.js

const ZH_CN = {
  login: {
    title: 'User login'
  },
}
export default ZH_CN

index.js

import { createI18n } from 'vue-i18n/index'
import 'dayjs/locale/zh-cn'
import zh from './zh-cn'
import en from './en'
import pl from './pl-pl'
const messages = {
  'zh-cn': zh,
  'en': en,
  'pl': pl
}
// Gets the current locale
export function getLanguage() {
  // Use the language of choice 
  const chooselang = localStorage.getItem('locale')
  if (chooselang) return chooselang
  // if not choose language
  const lang = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  return locales.includes(lang) ? lang : 'zh-cn'
}
const i18n = createI18n({
  locale: getLanguage(),
  fallbackLocale: 'en',
  global: true,
  messages
})
export function $t(args) {
  return i18n.global.tc(args)
}
console.log($t('login.title'))
export default (app) => {
  app.use(i18n)
}

illustrate

The getLanguage function determines whether the current localStorage has a selected language. If not, it gets the language of the current browser.
Encapsulate the $t function and export it for use in js files

3. In main.js

import language, { getLanguage, $t } from './language'
language(app)

4. Use in vue file

<template>
    //1. 
	<div class="login clamp ta-c fs-28 fw-b m-b10">{{ $t('login.title') }}</div>
	//2.
	<el-input v-model="$t('login.title')"></el-input>
</template>

How to switch language dynamically and change elementUI language?

1. Use vuex to write a method in mutations to change the element language

//---------------------- state-----------------------------
import { getLanguage } from '@/language'
const state = {
  lang: getLanguage()
}
export default state
//---------------------- mutations-----------------------------
import * as Types from './types'
import locale from 'element-plus/lib/locale'
import localeZH from 'element-plus/lib/locale/lang/zh-cn'
import localeEN from 'element-plus/lib/locale/lang/en'
import localePL from 'element-plus/lib/locale/lang/pl'
const element = {
  'zh-cn': localeZH,
  'en': localeEN,
  'pl': localePL
}
const mutations = {
  // Switch language [Types.SET_LANG](state, lang) {
    state.lang = lang
    localStorage.setItem('locale', lang)
    locale.use(element[lang])
  }
}
export default mutations
//------------------------- types-----------------------------
export const SET_LANG = 'SET_LANG'

2. Use

import * as Types from '@/store/types'
import { useI18n } from "vue-i18n";
export default {
  setup(props,ctx) {
    const { locale: lang } = useI18n({ useScope: "global" })
    let store = useStore()
    const handelLanguage = (name) => {
      lang.value = name
      store.commit(Types.SET_LANG, name)
    }
    return {
      handelLanguage
    }
  }
}

After changing the elementUI component view, it is not updated?

At this point you will find that even if we submit a commit to change the language page of elementUI, there is no change, because the view component is not updated. How can we refresh the component to reload it?

1. Control view display/hide on router-view

//---------------------- template-----------------------------
<router-view v-if="isReloadRouter"/>
//---------------------- script-----------------------------
const reload = () => {
	 state.isReloadRouter = false
     nextTick(() => {
       state.isReloadRouter = true
     })
}
provide("reload", reload)
<-- introduce provide nextTick ->

2. Call reload when switching languages

 const handelLanguage = (name) => {
      lang.value = name
      store.commit(Types.SET_LANG, name)
      inject('reload')()
    }

3. You need to call commit in main.js, otherwise the language will not be changed when you enter elementUI for the first time

import language, { getLanguage, $t } from './language'
import '@/styles/elementDefault.scss'
store.commit(Types.SET_LANG, getLanguage())

How to use $t function globally? How to use vue-i18n in js files?

Globally hang on the $t function and use the $t function directly in the js file.

Method 1: Hang it globally through app.config.globalProperties

Method 2: Implemented through provide and inject

import language, { getLanguage, $t } from './language'
const app = createApp(App);
//---------------------- app.config.globalProperties-----------------------------
app.config.globalProperties.$t = $t
// Use import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
proxy.$t()
// ----------------------- provide, inject -----------------------------
// app.provide('$t', $t) in main.js
// Using const $t = inject('$t')
ElMessage.warning({
  message: $t('login.warnMessage'),
   type: 'warning'
 });
Vue3 does not recommend mounting something on the prototype chain, but rather recommends using provide and inject, so it is best to use provide and inject through dependency and injection

You cannot use $t directly in router.js, you need to import this function yourself

import { $t } from '@/language'
{
        path: '/mainManage/device',
        name: 'device',
        hidden: false,
        meta: { icon: 'circle', title: $t('router.device') },
        component: () =>
          import(/* webpackChunkName: "device" */ '@/views/mainManage/device')
      },

There is a problem at present: because the field displayed in my menu is taken from the title in the routing information, router.js is only called when the project is first entered. When the language is switched, the menu field will not switch dynamically. It will only change when the browser is refreshed. If there is a solution, please leave a message to let me know! ! !

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of how to use element-plus in Vue3
  • Implementation of vite+vue3.0+ts+element-plus to quickly build a project
  • Steps to build the vite+vue3+element-plus project
  • Ideas for implementing multi-language switching in Vue projects
  • How to use vue-i18n to achieve multi-language switching effect
  • Use vue internationalization i18n to implement multiple language switching functions
  • Using vue-i18 plug-in in Vue to realize multi-language switching function

<<:  When to use table and when to use CSS (experience sharing)

>>:  MySQL Basics Quick Start Knowledge Summary (with Mind Map)

Recommend

Handwriting implementation of new in JS

Table of contents 1 Introduction to the new opera...

Native JS to implement hover drop-down menu

JS implements a hover drop-down menu. This is a s...

MYSQL A question about using character functions to filter data

Problem description: structure: test has two fiel...

Commonplace talk about MySQL event scheduler (must read)

Overview MySQL also has its own event scheduler, ...

SVG button example code based on CSS animation

The specific code is as follows: <a href="...

How to quickly copy large files under Linux

Copy data When copying data remotely, we usually ...

Detailed explanation of the binlog log analysis tool for monitoring MySQL: Canal

Canal is an open source project under Alibaba, de...

Pure CSS to achieve the water drop animation button in Material Design

Preface You should often see this kind of special...

Example code for using text-align and margin: 0 auto to center in CSS

Use text-align, margin: 0 auto to center in CSS W...

Use nginx to dynamically convert image sizes to generate thumbnails

The Nginx ngx_http_image_filter_module module (ng...

File upload via HTML5 on mobile

Most of the time, plug-ins are used to upload fil...