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

HTML simple shopping quantity applet

This article shares a simple HTML shopping quanti...

How to solve the problem that MySQL cannot start because it cannot create PID

Problem Description The MySQL startup error messa...

JavaScript clicks the button to generate a 4-digit random verification code

This article example shares the specific code of ...

Analyze how a SQL query statement is executed in MySQL

Table of contents 1. Overview of MySQL Logical Ar...

Friendly Alternatives to Find Tool in Linux

The find command is used to search for files in a...

Solution to MySQL error code 1862 your password has expired

The blogger hasn't used MySQL for a month or ...

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...

Detailed explanation of jQuery's copy object

<!DOCTYPE html> <html lang="en"...

How to ensure that every page of WeChat Mini Program is logged in

Table of contents status quo Solution Further sol...

A comprehensive understanding of Vue.js functional components

Table of contents Preface React Functional Compon...

Bootstrap 3.0 study notes buttons and drop-down menus

The previous article was a simple review of the B...

Detailed explanation of the principle and usage of MySQL stored procedures

This article uses examples to explain the princip...

JavaScript to achieve mouse drag effect

This article shares the specific code of JavaScri...