vue的组件之间方法以及变量的调用

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是返回值
    
})

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值