【vue】vue子孙组件传值(多级嵌套)attrs listeners

如果vue开发遇到多层嵌套,
子孙组件之间传值,
可以使用 attrs listeners传值。

在这里插入图片描述

在这里插入图片描述

示例如下:
孙子组件:

<template>
    <div class="wrap">
        孙子组件
        {{code.code1}}
        <button @click="func">click</button>
    </div>
</template>

<script>
    export default {
        name: "grandson",
        props:{
            code:{
                type:Object,
                default:()=>{}
            }
        },
        data(){
            return{

            }
        },
        mounted(){
            console.log(this.$attrs)
        },
        methods:{
            func(){
                console.log("发射---》")
                this.$emit('msg',"可以")
            }
        }
    }
</script>

<style scoped>
    .wrap{
        width: 30%;
        height: 100vh;
        border: solid 5px;
    }
</style>

父组件:

<template>
<div class="wrap">
 父组件
    <grandson :code="$attrs" v-on="$listeners"></grandson>
</div>
</template>

<script>
    import grandson from './grandson'
    export default {
        name: "father",
        components:{
            grandson
        },
        /*props:{
            code:{
                type:String,
                default:''
            }
        },*/
        mounted(){
            console.log("父组件---->",this.$attrs)

        }
    }
</script>

<style scoped>
    .wrap{
        width: 70%;
        height: 100vh;
        border: solid 5px;
    }
</style>

祖父组件

<template>
<div class="wrap">
    祖父组件{{str}}
    <father :code="code" :code1="code1" @msg="msg"></father>
</div>
</template>

<script>
    import father from './father'
    export default {
        name: "grandFather",
        components:{
            father
        },
        data(){
            return{
                code:"2023",
                code1:"2022",
                str:''
            }
        },
        methods:{
            msg(a){
                console.log("接收msg--->",a)
                this.str=a
            }
        }
    }
</script>

<style scoped>
.wrap{
    width: 100%;
    height: 100vh;
    border: solid 5px;
}
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值