Vue2 如何使用i18n(看完必会) 您所在的位置:网站首页 vue2停止维护了怎么办 Vue2 如何使用i18n(看完必会)

Vue2 如何使用i18n(看完必会)

2024-07-04 15:42| 来源: 网络整理| 查看: 265

1.需求分析 项目中需要使用到中英切换、两种或者多种语言切换时。就需要用到 i18n 这个库。i18n 不仅可以让我们的项目实现语言切换、更可以使我们的项目走向国际化!!!        2.安装 npm install [email protected] --save

这里有个疑问,为什么要安装8版本的vue-i18n呢。

原因在于: 因为我们的是vue2 的项目。如果我们直接使用 npm install vue-i18n 大抵是会报错的。

**peer vue@“^3.0.0” from [email protected] ** 这段意思是 版本不匹配

所以我们需要给vue-i18n 降级

我们可以使用下面命令查看 vue-i18n 所有版本:

npm view vue-i18n versions --json

这里我选择的是8.2.1版本。执行命令就不会报错了

3.使用 首先在我们src根目录下新建这几个文件

en.js

/** * Blogs 小猪宰汁 * Date: 2023/3/2 * filename:en.js */ export const h = { system: "Background management system", full: "full-screen display", account: "myAccount", invoice: "invoice", reconciliation: "Statement", record: "recording", report: "report", setting: "Settings", login: "login", tips: "Username and password are filled in casually", administrator: "administrator", placeUser: "please enter user name", palcePass: "Please enter your password", palceCode: "please enter verification code", accounts: "accounts", password: "password", code: "Verification code" }

zh.js

/** * Blogs 小猪宰汁 * Date: 2023/3/2 * filename:zh.js */ export const h = { system: "Vue后台管理系统", full: "全屏显示", account: "我的账户", invoice: "原始单据", reconciliation: "财务对账", record: "对账记录", report: "月结报表", setting: "系统设置", login: "登录", tips: "用户名和密码随便填", administrator: "管理员", placeUser: "请输入用户名", palcePass: "请输入密码", palceCode: "请输入验证码", accounts: "账号", password: "密码", code: "验证码" }

index.js

import Vue from "vue"; import VueI18n from "vue-i18n"; Vue.use(VueI18n); // 全局挂载 export const i18n = new VueI18n({ locale: localStorage.getItem("locale") || "en", // 从localStorage中获取 默认英文 messages: { zh: require("./lan/zh"), // 中文语言包 en: require("./lan/en") // 英文语言包 } }); export default i18n;

        2.随后我们在我们的入口文件main.js里 

import { i18n } from './i18n/index' //国际化 new Vue({ el: '#app', router, store,//使用store i18n, //使用国际化 components: { App }, template: '' }) 4.用法实例 {{language}} export default { data (){ return { language: localStorage.getItem("lang") ||"EN" } }, methods:{ changeLangEvent(){ console.log(this.$i18n); if (this.language == "EN"){ localStorage.setItem("locale", "zh"); this.$i18n.locale = localStorage.getItem("locale"); this.$message({ message:"切换为中文!", type:"success" }); localStorage.setItem("lang", "ZH"); this.language = "ZH"; location.reload(); //重新加载 } else if (this.language == "ZH"){ localStorage.setItem("locale", "en"); this.$i18n.locale = localStorage.getItem("locale"); this.$message({ message:"Switch to English!", type:"success" }); localStorage.setItem("lang", "EN"); this.language = "EN"; location.reload(); } } }

我们在需要切换语言的文字中

{{$t('h.system')}}

以上就是关于vue2如何使用i18n的介绍与步骤 简单的一些整理 哪里有不对的 或者有写错的 就在下面留言 我们共同进步 ~~~~                                                       



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有