安裝vue
npm install vue-i18n
新建一個文件夾 i18n ,內新建 en.js zh.js index.js 三個文件npm
準備翻譯信息app
en.js學習
export default { home: { helloworld: "hello workd !" } };
zh.jsthis
export default { home: { helloworld: "你好世界" } };
index.jsspa
建立Vue-i18n實例prototype
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.jscode
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");
簡單的使用router
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 裏面,由於當語言切換的時候 他是不會變的 ,要寫在computed內
此隨筆乃本人學習工做記錄,若有疑問歡迎在下面評論,轉載請標明出處。
若是對您有幫助請動動鼠標右下方給我來個贊,您的支持是我最大的動力。