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 @   lijun12138  阅读(308)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示