首页 > 技术文章 > vue中的父子组件问题

lvlv11 2021-07-22 11:50 原文

1.prop传值延迟问题

解决办法:

    a.给prop默认值

    b.直接在父级给子组件赋值:this.$refs.statisticsInfo.selectedData = this.selected[0];

  有时调用失败是因为子组件没有渲染完成

    this.$nextTick(() => {this.$refs.showImg.initPage(this.componentForm);})
  可通过this.$nextTick()方法,加载完成后执行函数解决

 

2.父级可以通过this.$refs直接调用子组件的属性和方法

    例:this.$refs.statisticsInfo.selectedData = this.selected[0];

           this.$refs.statisticsInfo.beforess();

 

3.$emit可以调用父组件的方法

    this.$emit('showCityName',data);   

    第一个参数是父组件的方法:

    <Child @showCityName="updateCity"/>

    第二个参数是父组件方法的参数

     updateCity(data){//触发子组件城市选择-选择城市的事件

             this.toCity = data.cityname;//改变了父组件的值

             console.log('toCity:'+this.toCity);

          }

 

4.可在子组件的方法中直接用 this.$parent.父组件方法

 

推荐阅读