🧑🎓 个人主页:Silence Lamb
📖 本章内容:【国际化语言配置】
Silence-Vue v1.0.0
基于VUE前端快速开发框架
🍎平台简介
一、创建工具类
1.1🍖【本地缓存】
- 🍖本地缓存 | 会话级缓存:src\utils\tools\cache.js
/*
* @Description : 本地缓存 | 会话级缓存
* @Author : SilenceLamb
* @Version : V1.0.0
*/
const sessionCache = {
/**
* @Description : 设置会话级缓存
* @param {string} key 缓存键
* @param {string} value 缓存值
*/
set(key, value) {
if (!sessionStorage) {
return
}
if (key != null && value != null) {
sessionStorage.setItem(key, value)
}
},
/**
* @Description : 获取会话级缓存值
* @param {string} key 缓存键
* @return { }
*/
get(key) {
if (!sessionStorage) {
return null
}
if (key == null) {
return null
}
return sessionStorage.getItem(key)
},
setJSON(key, jsonValue) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue))
}
},
getJSON(key) {
const value = this.get(key)
if (value != null) {
return JSON.parse(value)
}
},
remove(key) {
sessionStorage.removeItem(key)
},
/**
* @Author : SilenceLamb
* @Description : 本地缓存
*/
}
const localCache = {
set(key, value) {
if (!localStorage) {
return
}
if (key != null && value != null) {
localStorage.setItem(key, value)
}
},
get(key) {
if (!localStorage) {
return null
}
if (key == null) {
return null
}
return localStorage.getItem(key)
},
setJSON(key, jsonValue) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue))
}
},
getJSON(key) {
const value = this.get(key)
if (value != null) {
return JSON.parse(value)
}
},
remove(key) {
localStorage.removeItem(key)
},
}
export default {
/**
* 会话级缓存
*/
session: sessionCache,
/**
* 本地缓存
*/
local: localCache,
}
1.2🍖【语言管理】
- 🍖状态管理:src\utils\tools\language.js
/**
* @Description : 网站信息管理
* @Author : SilenceLamb
* @Version : V1.0.0
*/
import defaultSettings from '@/constant/settings'
const { siteLang } = defaultSettings
/**
* 可能是在一个 Vuex store 中作为状态的初始值进行定义
* @type {lang} 语言
* @type {title} 网站标题
* @type {logo} 网站logo
* @type {fixedHeader} 头部固定
* @type {sidebarLogo} 是否显示Logo
*/
const state = {
siteLang: siteLang,
}
/**
* 用于存储更改应用程序状态的函数
* 这些函数通常在 actions 中被调用
*/
const mutations = {
/**
* 更改设置
* @param state state对象
* @param key state属性
* @param value 给定的值
* @constructor
*/
CHANGE_SETTING: (state, { key, value }) => {
if (Object.hasOwnProperty.call(state, key)) {
state[key] = value
}
},
}
/**
* 用于存储异步操作的函数
* 通常用于执行一些异步操作
*/
const actions = {
/**
* 更改设置
* @param commit
* @param data { key:'', value:''}
*/
changeSetting({ commit }, data) {
commit('CHANGE_SETTING', data)
},
}
export default {
namespaced: true,
state,
mutations,
actions,
}
- 🍖语言管理:src\utils\tools\language.js
/*
* @Description : 语言管理工具
* @Author : SilenceLamb
* @Version : V1.0.0
*/
import store from '@/store'
import cache from './cache'
export default {
/**
* @Description 获取lang语言设置
* @returns {string} 语言种类
*/
getLanguage() {
const chooseLanguage = cache.local.get('language')
if (chooseLanguage) {
return chooseLanguage
} else {
return store.state.settings.siteLang
}
},
/**
* @Description 设置语言种类
* @param {string} lang 语言
*/
setLanguage(lang) {
cache.local.set('language', lang)
store.dispatch('settings/changeSetting', { key: 'siteLang', value: lang }).then()
},
}
二、切换语言组件
- 🛞语言管理:src\components\LangSelect
<!--
* @Description : 语言切换
* @Author : SilenceLamb
* @Version : V1.0.0
-->
<template>
<el-dropdown trigger="click" class="international" @command="handleSetLanguage">
<div>
<svg-icon class-name="international-icon" icon-class="language" />
</div>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item :disabled="language === 'zh'" command="zh">
{{ $t('language.Chinese') }}
</el-dropdown-item>
<el-dropdown-item :disabled="language === 'en'" command="en">
{{ $t('language.English') }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</template>
<script>
import { setLanguage } from '@/utils/modules/common'
export default {
name: 'LangSelect',
computed: {
language() {
return this.$store.state.settings.siteLang
},
},
methods: {
/**
* @Description : 切换语言操作
* @param {String} lang 语言种类
*/
handleSetLanguage(lang) {
setLanguage(lang)
this.$i18n.locale = lang
this.$message({
message: 'Switch Language Success',
type: 'success',
})
},
},
}
</script>
三、国际化配置
3.1🌳【语言资源包】
- 🌳中文:src\language\modules\utils\zh\index.js
/*
* @Description : 国际化资源-中文
* @Author : SilenceLamb
* @Version : V1.0.0
*/
export default {
/**
* @Description : language.js
*/
language: {
Chinese: '中文',
English: '英文',
},
}
- 🌳英文:src\language\modules\utils\en\index.js
/*
* @Description : 国际化资源-英文
* @Author : SilenceLamb
* @Version : V1.0.0
*/
export default {
/**
* @Description : language.js
*/
language: {
Chinese: 'Chinese',
English: 'English',
},
}
3.2🌳【加载语言资源】
- 🌳加载语言资源:src\language\index.js
/*
* @Description : 加载语言包
* @Author : SilenceLamb
* @Version : V1.0.0
*/
import { createI18n } from 'vue-i18n'
import language from '@/utils/tools/language'
import fileNameUtils from '@/utils/tools/fileName'
import elementEnLocale from 'element-plus/lib/locale/lang/en' // element-plus lang
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn' // element-plus lang
/**
* 准备要合并的语言包
* @type {{en: *[], "zh-cn": *[]}}
*/
const assignLocale = {
zh: [elementZhLocale],
en: [elementEnLocale],
}
/**
* @Description 获取最后一个文件夹
* @param {string} filePath
* @returns {string} fileName 子文件夹名
*/
getLastFileName(filePath) {
const matches = filePath.substring(0, filePath.lastIndexOf('/')).split('/').pop()
return matches
}
/**
* @Description : 加载在 modules 目录中动态加载语言包
* @return {{}} 语言源
*/
export function loadLang(language) {
const messages = {
zh: [],
en: [],
}
const messagePack = require.context('./modules/', true, /\.js$/)
messagePack.keys().forEach((filePath) => {
const localeMessage = messagePack(filePath).default
const fileName = getLastFileName(filePath)
//合并语言包
assignLocale[fileName].push(localeMessage)
Object.assign(messages[fileName], ...assignLocale[fileName])
})
return messages
}
- 🌳国际化配置:src\language\index.js
const i18n = new createI18n({
locale: language.getLanguage(),
legacy: false, // 让 setup 函数可以通过 t 访问
globalInjection: true, // 让 template 可以像 vue2 那样使用 $t 来访问
fallbackFormat: 'en',
messages: loadLang(language.getLanguage()),
})
export default i18n
- 🌳全局引入:src\main.js
import { createApp } from 'vue'
import App from './App.vue'
import i18n from '@/language' // 我是把i18n单独放一个文件夹,这里是引用
const app = createApp(App)
app.use(i18n)
app.config.productionTip = false // 阻止 vue 在启动时生成生产提示
app.mount('#app')
四、使用国际化
4.1🍑【组件中使用】
<template>
<div class="app-container">
{{ $t('language.Chinese') }}
<el-button type="primary" @click="get">loading</el-button>
</div>
</template>
<script>
export default {
name: 'IndexVue',
data() {
return {
lang: 'hello',
}
},
watch: {},
methods: {
get(){
console.log(this.$t('language.Chinese'));
}
},
}
</script>
4.2🍑【JS文件使用】
/*
* @Description : 文本复制功能
* @Author : SilenceLamb
* @Version : V1.0.0
*/
import Clipboard from 'clipboard'
import model from '@/utils/tools/model'
import {i18n}from '@/language'
/**
* @Description 复制文本
* @param {String} text - 文本
* @param {event} event - 事件
*/
export function handleClipboard(text, event) {
const clipboard = new Clipboard(event.target, { text: () => text })
clipboard.on('success', () => {
clipboardSuccess()
clipboard.destroy()
})
clipboard.on('error', () => {
clipboardError()
clipboard.destroy()
})
clipboard.onClick(event)
}
/**
* @Description 复制成功
* @return {string} 成功
*/
export function clipboardSuccess() {
model.notifySuccess(i18n.global.t('copy.Success'))
}
/**
* @Description 复制失败
* @return {string} 失败
*/
export function clipboardError() {
model.notifyError(i18n.global.t('copy.Failed'))
}
4.3🍑 【菜单中使用】
/**
* 菜单标题
* @param title 标题
* @return {*} title | this.$t(`router.` + title)
*/
routerTitle(title) {
if (this.$t(`router.` + title)) {
return this.$t(`router.` + title)
} else {
return title
}
},
4.4🍑【手动切换语言】
handleSetLanguage(lang) {
this.$i18n.locale = lang
this.$message({
message: 'Switch Language Success',
type: 'success',
})
},