vue父与子组件,子与子组件间的方法调用和通信

 

子与子之间通信的前提是有一个共同的父亲,

首先,在vue中,$+name是vue系统定义的实例属性或方法,vue的api上面写的有链接实例属性

$parent指的是当前组件的父实例。$refs指的是一个对象,持有注册过 ref特性 (ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。链接ref注册)的所有 DOM 元素和组件实例。

使用$emit子传父和props父传子比较繁琐不建议使用。

能相互调用方法就能相互通信,改变各自组件 的属性值

方法里如果需要参数还可以传递参数

子组件对父组件的方法的调用:this.$parent.fatherMethod(....)。还能隔辈引用,this.$parent.$parent,对爷爷辈的引用。

父组件对子组件方法的调用:this.$refs.childRef.childMethod(....)。前提要在标签上注册ref特性,如下demo

子组件1对子组件2的方法调用:this.$parent.$refs.child2Ref.child2Method(...),同样可推隔辈使用的方法。

下面有程序小样,可供参考

父组件的code

<template>
<div id="parent">
    <child1Label ref="child1Ref"><!--这里一定要通过ref注册,父组件才能调用子组件方法-->

    </child1Label>
    <child2Label ref="child2Ref">

    </child2Label>
    <button @click="fatherMethod2">调c2方法</button>
</div>
</template>
<script>
import child1 from "@/components/child1"
import child2 from "@/components/child2"

export default{

    data(){
        return{

        }
    },
    methods:{
        fatherMethod1:function(){
              console.log('这是父组件的方法');
        },//子组件能调用父组件方法,就能通过方法修改父组件属性字段的值,也就相当于实现了通信功能
        fatherMethod2:function(){
            this.$refs.child2Ref.child2Method();
        }
    },

    components:{
        child1Label:child1,
        child2Label:child2,

    },



}
</script>
<style scoped>
    
</style>

子组件的code 

<template>
<div id="child1">
    <button @click="child1Method">子组件1</button>
</div>
</template>
<script>
export default{
    data(){
        return{

        }
    },
    methods:{
        child1Method:function(){
              console.log('这里使子组件1的方法');
               this.$parent.fatherMethod1();//调用父组件的方法
               this.$parent.$refs.child2Ref.child2Method();//调用子组件2的方法
        }
    },
}
</script>
<style scoped>
    
</style>

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值