其他分享
首页 > 其他分享> > vue项目实现中英文切换

vue项目实现中英文切换

作者:互联网

转载自:https://www.cnblogs.com/fczbk/p/14468037.html

1、首先安装插件vue-i18n

1 npm install vue-i18n --save-dev

2、创建文件

 en.ts 文件内容

1 2 3 4 5 6 7 8 module.exports = {   language: {     name: '英文',   },   about: {     title: 'I am English',   }, };

zh.ts 文件内容

1 2 3 4 5 6 7 8 module.exports = {   language: {     name: '中文',   },   about: {     title: '我是中文',   }, };

index.ts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 // 中英文切换 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

1 2 3 4 5 6 7 8 import i18n from './components/language/index';   new Vue({   router,   store,   i18n,   render: (h) => h(App), }).$mount('#app');

 DEMO

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <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>

标签:vue,zh,中英文,language,ts,Vue,切换,i18n
来源: https://www.cnblogs.com/Insist-Y/p/15643940.html