vue国际化之vue-i18n使用

npm install vue-i18n --save

main.js

import Vue from 'vue';
import App from './App.vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);
import * as zh from './config/zh';
import en from './config/en';
console.log('zh', zh);
console.log('en', en);
Vue.config.productionTip = false;
const i18n = new VueI18n({
  locale: 'zh', // 语言标识
  //this.$i18n.locale // 通过切换locale的值来实现语
  messages: {
    zh: require('./config/zh'), // 中文语言包
    en: require('./config/en') // 英文语言包
  }
});
new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app');

 en.js

export const m = {
  music: 'Music', //网易云音乐
  findMusic: 'FIND MUSIC', //发现音乐
  myMusic: 'MY MUSIC', //我的音乐
  friend: 'FRIEND', //朋友
  musician: 'MUSICIAN', //音乐人
  download: 'DOWNLOAD' //下载客户端
};

zh.js

export const m = {
  music: '网易云音乐',
  findMusic: '发现音乐',
  myMusic: '我的音乐',
  friend: '朋友',
  musician: '音乐人',
  download: '下载客户端'
};

vue

<template>
  <div>
    <div>{{ $t('m.music') }}</div>
    <div>{{ $t('m.myMusic') }}</div>
    <button @click="change">{{ lang }}</button>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      lang: '中文',
      state: true
    };
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    change() {
      this.state = !this.state;
      if (this.state === true) {
        this.lang = '中文';
        this.$i18n.locale = 'zh-CN';
      } else {
        this.lang = 'English';
        this.$i18n.locale = 'en-US';
      }
    }
  }
};
</script>
<style lang="less" scoped>
</style>
原文地址:https://www.cnblogs.com/lsc-boke/p/14522580.html