微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐