vue 中使用 國際化(i18n)


效果圖

第一步

  • 安裝插件
  • npm install vue-i18n --save
  • 打開package.json 文件查看 vue-i18n

第二步

  • 在assets文件下新建文件夾language
  • 包含 index.js,language-CN.js, language.EN.js 三個文件

第三步 - 編寫代碼

  • index.js 文件如下
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import enLocale from './language-EN'
import usLocal from './language-CN'
Vue.use(VueI18n);
const messages = {
    en: {
        ...enLocale
    },
    cn: {
        ...usLocal
    }
}
const i18n = new VueI18n({
    locale: localStorage.getItem('lang') || 'cn',
    messages,
});

export default i18n;
  • language-cn.js 代碼如下
export default {
    message: {
        'hello': '你好 世界',
        'desc': 'Ant Design 是西湖區最具影響力的 Web 設計規范',
        'loginAccount': '賬戶密碼登錄',
        'loginByPhone': '手機號登錄',
        'account': '賬戶',
        'password': '密碼',
        'autoLofin': '自動登錄',
        'forgetPassword': '忘記密碼',
        'loginBtn': '登錄',
        'otherLoginWay': '其他方式登錄',
        'register': '注冊',
        'help': '幫助',
        'privacy': '隱私',
        'clause': '條款',
        'phone': '手機號',
        'code': '驗證碼',
        'getCode': '獲取驗證碼',
    }
};
  • language-en.js 代碼如下

export default {
    message: {
        'hello': 'hello world',
        'desc': 'Ant Design is the most influential web design specification in Xihu district',
        'loginAccount': 'Credentials',
        'loginByPhone': 'Mobile number',
        'account': 'Account',
        'password': 'password',
        'autoLofin': 'Remember me',
        'forgetPassword': 'Forgot your password?',
        'loginBtn': 'Login',
        'otherLoginWay': 'Sign in with',
        'register': 'Sign up',
        'help': 'help',
        'privacy': 'privacy',
        'clause': 'clause',
        'phone': 'Mobile Number',
        'code': 'Verification code',
        'getCode': 'Get code',
    }
}

第四步

  • 在main.js 中使用
import i18n from './assets/language/index';
new Vue({
    router,
    i18n,
    render: h => h(App),
}).$mount('#app')

第五步 - 在頁面中使用

// 文本描述
{{$t('message.desc')}}

// 輸入框默認填充字符
:placeholder="$t('message.phone')"

本文只是簡述使用方法(登錄頁面的內容),沒有對所有頁面進行結構划分,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM