A06-国际化语言配置

SilenceVue是一个基于Vue的前端开发框架,文章详细介绍了其如何实现本地缓存(包括会话级缓存和本地缓存)以及语言管理。语言管理部分包括了状态管理、语言设置的获取与设置,以及一个用于切换语言的组件。此外,文章还展示了如何配置语言资源包和使用国际化功能,包括加载语言资源和在组件、JS文件及菜单中使用i18n。
摘要由CSDN通过智能技术生成

🧑‍🎓 个人主页Silence Lamb
📖 本章内容:【国际化语言配置


Silence-Vue v1.0.0

基于VUE前端快速开发框架

在这里插入图片描述

🍎平台简介

star star star star star star


一、创建工具类

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',
  })
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Silence Lamb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值