1、父组件调用子组件 

  (1)方法


 方式①:通过ref直接调用子组件的方法

父组件:

<children ref="child"></children>

this.$refs.child.getDetail();

子组件:

mounted(){
	getDetail(){
		console.log('子组件')
	}
}

 方式②:通过组件的$emit$on方法(----此方式忽略-----)

(2)变量 


方式①:通过子组件调用父组件的方法,子组件主动将值传递给父组件

 父组件:

functionA(transVal){
    this.getVal = transVal
}

子组件:

this.$emit('functionA',this.tVal)

方式②:通过$refs来主动获取子组件中的值(与调用子组件方法一致) 

this.parenVal = this.$refs.child.childVal

2、子组件调用父组件  

        (1)方法


方式①:在子组件中通过this.$parent.event来调用父组件的方法

父组件:

hasCancleBtn(){
        console.log('父组件')
    },

 子组件:

this.$parent.hasCancleBtn();

方式②:父组件中将方法作为属性传入子组件,在子组件里props申明后直接调用这个方法即可

父组件:

<children :hasCancleBtn="hasCancleBtn"></children>

hasCancleBtn(){
	console.log('父组件')
}

子组件:

<div @click="hasCancleBtn"></div

props: {
    hasCancleBtn: {
      type: Function,
      default:function() {
        console.log('test')
      }
    }
  },


 方式③:子组件中用$emit向父组件触发一个事件

父组件:

<children @has-cancle-btn="hasCancleBtn"></children>

hasCancleBtn(){
	console.log('父组件')
}

子组件: 

<div  @click="$emit('has-cancle-btn')"></div>

(2)变量


父组件:

step1:导入组件

import OneCompoment  from "@/componments/OneCompomen.vue";

step2:注册组件

components:{
    OneCompoent,
},

step3:使用组件,传递值给子组件

<OneCompoent :infomation="infomation"></OneCompoent>

在这里插入图片描述

子组件:

step1:接收父组件传递的值

props:{
    infomation:{
        type:String,
        default:''
    }
},

// 或者
props:{
    ['infomation']
}.

step2:使用该变量

<div>{{infomation}}</div>

functionA(){
    console.log(this.infomation)
}

在这里插入图片描述

3、同级组件(无关系组件)之间方法的调用 

****注意:调用组件的方法都是异步方法,如果想做成同步的方法,需要通过callback设定返回值,达到同步的效果****,如下: 

父组件:

    async submitProjectInfo(callback = () => {}) {
      // 调用节点信息设置组件的提交方法
      this.$refs.nodeInfoChild.finalSubmit()
      callback(true)
    }

子组件:

this.$emit('submitProjectInfo', res => {

    // res是返回值
    
})

Logo

前往低代码交流专区

更多推荐