Vuejs2.0的坑--Element UI 中的el-dialog包含子组件时,报错解决:TypeError: Cannot read property 'setActiveItem' of ...

真是坑,在el-dialog中使用el-carousel组件,想要动态修改幻灯片的当前激活的索引,element官网给出的文档写着可以用setActiveItem方法改变,但一直给我报setActiveItem这个方法undefined...调试了两个小时终于找到了原因:

html代码
改变索引

    
        
            图片
        
    

js代码,原本我是这样写的
showRemarkPic: function (index) {
    var self = this;
    self.dialogRemarkImg = true;//显示弹框
    self.$refs.remarkCarousel.setActiveItem(index);
},

运行报错:Cannot read property 'setActiveItem' of undefined
然后就是悲剧的调试了两个小时,各种怀疑人生。。。。
打印了self.$refs.remarkCarousel输出undefined

console.log(self.$refs.remarkCarousel); //undefined

恍然大悟,可能是因为打开dialog的时候组件还未生成,用了一个延时函数setTimeout解决问题

js代码,下面是正确用法
showRemarkPic: function (index) {
    var self = this;
    self.dialogRemarkImg = true;//显示弹框
    setTimeout(function () {//等组件生成再调用setActiveItem(index);
        self.$refs.remarkCarousel.setActiveItem(index);
    }, 500);
},

果然是这个原因,解决问题

tips: 上交流可能会看不到消息,如有问题,欢迎进群交流50063010

end------------------------------------

你可能感兴趣的:(Vuejs2.0的坑--Element UI 中的el-dialog包含子组件时,报错解决:TypeError: Cannot read property 'setActiveItem' of ...)