使用vue 國際化i18n 實現(xiàn)多實現(xiàn)語言切換功能
安裝
npm install vue-i18n
新建一個文件夾 i18n ,內(nèi)新建 en.js zh.js index.js 三個文件
準(zhǔn)備翻譯信息
en.js
export default {
home: {
helloworld: "hello workd !"
}
};
zh.js
export default {
home: {
helloworld: "你好世界"
}
};
index.js
創(chuàng)建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>
<script>
export default {
data: function() {
return {};
},
computed: {
hi() {
return this.$t("home.helloworld");
}
},
methods: {
changeLang() {
this.$i18n.locale = "en";
}
}
};
</script>
注意:
比如說上面的hi 你要通過這種形式來寫的時候,不能放在data 里面,因為當(dāng)語言切換的時候 他是不會變的 ,要寫在computed內(nèi)
總結(jié)
以上所述是小編給大家介紹的使用vue 國際化i18n 多實現(xiàn)語言切換功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
解決iview多表頭動態(tài)更改列元素發(fā)生的錯誤的方法
這篇文章主要介紹了解決iview多表頭動態(tài)更改列元素發(fā)生的錯誤的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
Vue結(jié)合ElementUI實現(xiàn)數(shù)據(jù)請求和頁面跳轉(zhuǎn)功能(最新推薦)
我們在Proflie.vue實例中,有beforeRouteEnter、beforeRouteLeave兩個函數(shù)分別是進(jìn)入路由之前和離開路由之后,我們可以在這兩個函數(shù)之內(nèi)進(jìn)行數(shù)據(jù)的請求,下面給大家分享Vue結(jié)合ElementUI實現(xiàn)數(shù)據(jù)請求和頁面跳轉(zhuǎn)功能,感興趣的朋友一起看看吧2024-05-05
vue如何在style標(biāo)簽中使用變量(數(shù)據(jù))詳解
在我們編寫css樣式中是不能直接使用vue data中的變量的,下面這篇文章主要給大家介紹了關(guān)于vue如何在style標(biāo)簽中使用變量(數(shù)據(jù))的相關(guān)資料,需要的朋友可以參考下2022-09-09

