安装
npm install vue-i18n
新建一个文件夹 i18n ,内新建 en.js zh.js index.js 三个文件
准备翻译信息
en.js
export default { home: { helloworld: "hello workd !" } };
zh.js
export default { home: { helloworld: "你好世界" } };
index.js
创建Vue-i18n实例
import Vue from "vue"; import VueI18n from "vue-i18n"; import enLocale from "./en"; import zhLocale from "./zh"; Vue.use(VueI18n); const i18n = new VueI18n({ locale: localStorage.lang || "zh", messages: { en: { ...enLocale }, zh: { ...zhLocale } } }); export default i18n;
i18n 挂载到 vue 根实例
main.js
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import i18n from "./assets/i18n/index"; Vue.config.productionTip = false; Vue.prototype.$i18n = i18n; new Vue({ router, store, i18n, render: h => h(App) }).$mount("#app");
简单的使用
about.vue
<template>
<div class="about">
<h1>{{ $t("home.helloworld") }}</h1>
<button @click="changeLang()">切换英文</button>
<p>{{hi}}</p>
</div>
</template>
< >
export default {
data: function() {
return {};
},
computed: {
hi() {
return this.$t("home.helloworld");
}
},
methods: {
changeLang() {
this.$i18n.locale = "en";
}
}
};
</ >
注意:
比如说上面的hi 你要通过这种形式来写的时候,不能放在data 里面,因为当语言切换的时候 他是不会变的 ,要写在computed内
此随笔乃本人学习工作记录,如有疑问欢迎在下面评论,转载请标明出处。
如果对您有帮助请动动鼠标右下方给我来个赞,您的支持是我最大的动力。
继续阅读与本文标签相同的文章
上一篇 :
阿里副总裁玄难:藏经阁计划首次在阿里应用落地
下一篇 :
OpenAI表示,AI系统需要证明自己
-
python运算符
2026-05-18栏目: 教程
-
史上最强多线程面试44题和答案:线程锁+线程池+线程同步等
2026-05-18栏目: 教程
-
9月最新184道阿里、百度、腾讯、头条Java面试题合集
2026-05-18栏目: 教程
-
美团携手世界粮食计划署共推“拒绝隐性饥饿”健康饮食倡导行动
2026-05-18栏目: 教程
-
圆通回应“承诺达”解散:由直营模式改回加盟商授权经营
2026-05-18栏目: 教程
