vue自定义i18n插件简单实现

实现方式:类似于在数据字典中查找对应的翻译

 <script src="./vue.js"></script>
  <div id="app">
    <h1>{{$t('welcome-message')}}</h1>
    <button @click="changeLang('en')">English</button>
    <button @click="changeLang('zh')">中文</button>
    <button @click="changeLang('nl')">Dutch</button>
  </div>
  <script>
    const i18nPlugin={
      install(Vue,locales){//locales是传入的options
    
    //Vue.mixin({
       //  methods:{
       //     $t(id){
       //       return locales[this.$root.lang][id]
       //     }
       //   }
       // }) mixin混入
        Vue.prototype.$t=function(id){//全局注册$t函数
          return locales[this.$root.lang][id]//返回id对应的内容,this.$root.lang访问根组件的响应数据,也可以使用vuex管理数据
        }
      }
    }

    Vue.use(i18nPlugin,{
      en:{'welcome-message':'hello'},//类似于数据字典
      zh:{'welcome-message':'你好'},
      nl: { 'welcome-message': 'Hallo' },
    })

    new Vue({
      el:'#app',
      data:{
        lang:'en'
      },
      methods:{
        changeLang(lang){
          this.lang = lang
        }
      }
    })
  </script>

 

posted @ 2022-06-11 18:44  lijun12138  阅读(313)  评论(0)    收藏  举报