this.$refs.xxx报Cannot read properties of undefined (reading ‘xxx‘)“

工作记录

背景:

父组件在通过this.$refs获取子组件的属性和方法

子组件:
        

//调用:
    handleAdd() {
      this.optype = "fence";
      //initfun()为子组件的方法
      this.$refs.setfenceref.initfun();
    },

报错:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: “TypeError: Cannot read properties of undefined (reading ‘initfun’)”

解决:

    handleAdd() {
      this.optype = "fence";
      this.$nextTick(()=>{
        this.$refs.setfenceref.initfun();
      })
    },

原因:

vue还没进行加载完子组件的方法的时候就开始进行执行子组件方法就会报这个错误,解决的办法很简单,只要在让方法在vue加载完子组件之后再进行执行

this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。

你可能感兴趣的:(vue,vue.js,javascript,前端)