首页 > Web开发 > 详细

Vue.js provide / inject 踩坑

时间:2019-12-26 02:43:34      阅读:612      评论:0      收藏:0      [点我收藏+]

最近学习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对象,

 

Vue.js provide / inject 踩坑

原文:https://www.cnblogs.com/maoyuanwai/p/12099534.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!