1、首先安装插件vue-i18n
npm install vue-i18n --save-dev
2、创建文件
en.ts 文件内容
module.exports = { language: { name: '英文', }, about: { title: 'I am English', }, };
zh.ts 文件内容
module.exports = { language: { name: '中文', }, about: { title: '我是中文', }, };
index.ts
// 中英文切换 import Vue from 'vue'; import VueI18n from 'vue-i18n'; Vue.use(VueI18n); const i18n = new VueI18n({ locale: localStorage.getItem('languageStorage') || 'zh', messages: { 'zh': require('./zh'), 'en': require('./en'), }, }); export default i18n;
3、在 mian.ts 引入i18n
import i18n from './components/language/index'; new Vue({ router, store, i18n, render: (h) => h(App), }).$mount('#app');
DEMO
<template> <div class="about"> {{ language }} <el-button-group> <el-button @click="setLanguage('zh')">中文</el-button> <el-button @click="setLanguage('en')">英文</el-button> </el-button-group> <h1>{{ $t('about.title') }}</h1> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component export default class About extends Vue { public language: string = localStorage.getItem('languageStorage') || 'zh'; private setLanguage(val: string) { localStorage.setItem('languageStorage', val); this.language = val; this.$i18n.locale = val; } } </script>