Vue.js provide / inject 踩坑

最近学习JavaScript,并且使用vuejs,第一次使用依赖注入,结果踩坑,差点把屏幕摔了。。始终获取不到如组件的属性,provide中的this对象始终是子组件的this对象

慢慢也摸索到了些vuejs的一些门门道道。。。。

错误代码1:this对象未定义错误

父组件
provide:{
            getCustomerId:this
        },


子组件
inject:['getCustomerId'],

子组件调用:
this.getCustomerId
//此时:getCustomerId 是未定义的

错误代码2:this对象未定义错误

父组件
provide:{
        getCustomerId(){
            return this
            }
        },


子组件
inject:['getCustomerId'],

子组件调用:
this.getCustomerId
//此时:返回的this是子组件的this,此时注入的是getCustomerId这个方法,而这个方法并未在组件的methods中声明

正确代码:

父组件
provide(){
            return { getCustomerId: this.getCustomerId}
        },
 
 
   methods: {
            getCustomerId(){

            },
      }

子组件
inject:['getCustomerId'],

子组件调用:
this.getCustomerId
//此时:此时就对了,注入的是父组件methods中定义的getCustomerId方法,并且provide()改成的方法定义,执行此方法时,provide中的this对象也是父组件的this对象,

猜你喜欢

转载自www.cnblogs.com/maoyuanwai/p/12099534.html