前端项目国际化-vue+vue-i18n

vue + vue-i18n

1.首先在main.js引入vue-i18n

import VueI18n from 'vue-i18n'
Vue.use(VueI18n);

2.然后引入语言包

const i18n = new VueI18n({
  locale: 'CN',    // 语言标识
  messages: {
    'CN': require('./assets/common/lang/zh.js'),   // 中文语言包
    'EN': require('./assets/common/lang/en.js')    // 英文语言包
  },
})
//语言包里可以如下定义
export const  message= {  //必须有导出export,另外两份语言包里面的定义结构要相同
    form:"switch the language",
    user:"userName",
    tel: "telephone",
    ID: "ID Number",
    button1:"search",
    button2: "reset",
}

3.将i18n 挂载到vue实例对象上

new Vue({
  el:'#app',
  i18n,
  router,
  template: '<App/>',
  components: { App }
})

4.在需要的组件里引用,例如

<template>
    <div class="hello">
        <div class="left">
            <p>
                <label> {{ $t('message.form') }}</label>
                <select v-model="locale">
                    <option>CN</option>
                    <option>EN</option>
                </select>
            </p>
            <p>
                <label>{{$t('message.user') }} </label>
                <input type="text" />
            </p>
            <p>
                <label>{{$t('message.tel') }} </label>
                <input type="text" />
            </p>
            <p>
                <label>{{$t('message.ID') }} </label>
                <input type="text" />
            </p>
            <p>
                <button>{{$t('message.button1') }} </button>
                <button>{{$t('message.button2') }} </button>
            </p>
        </div>
        <div class="right">
            <img :src= "imgSrc"  />
        </div>
    </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      locale: 'CN',     
     }
  },
  watch:{
    locale(val){
        this.$i18n.locale = val
    }
  },
  computed:{
    imgSrc: function(){
        return require(`../images/${this.locale}/timg.jpg`) //注意这里是替换图片用的
    }
  }
}
</script>

如果此篇对你没有帮助,可以到这个地址查阅: https://segmentfault.com/a/1190000009058572

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 来源:github.com Vue.js开源项目速查表:https://www.ctolib.com/cheats...
    zhangtaiwei阅读 11,879评论 1 159
  • 夜晚祸人心。 又是不自觉点开他的微信,把朋友圈早已翻兰的状态又重温一边,然而并不能回到第一次翻起的心情。 失恋期间...
    猫猫二小姐阅读 579评论 3 2
  • 因为某些原因,突然就看不见了,那一刻相信每个人都是恐慌而绝望的,但我却因此得到了好多好多的启示,而那些曾经想了很久...
    醉Lu巴黎阅读 279评论 0 0
  • 不要觉得,你在别人心目中占有多重要的位置,其实不然,别以为还是当初的梁山好汉。世界在改变,人也在改变,没有那个人会...
    文艺时光阅读 471评论 0 0

友情链接更多精彩内容