如果vue开发遇到多层嵌套,
子孙组件之间传值,
可以使用 attrs listeners传值。
![在这里插入图片描述](https://img-blog.csdnimg.cn/a5ab6e4dce2c459095797d7e89b3905b.png)
![](https://img-blog.csdnimg.cn/d781971baafc4f2ca936575c2c254f9b.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/e885c1ccf5144890aa30ffb3cf24e018.png)
示例如下:
孙子组件:
<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>