Article directory
Parent component passes value to child component:
1. Custom attributes in the parent component are received by the child component using props.
Parent component code:
<template>
<div>
<Page1 :tran="info"></Page1>
</div>
</template>
<script>
import Page1 from "./components4/Page1.vue"
export default {
data(){
return{
info:"我是父组件传过来的值"
}
},
components:{
Page1
}
}
Subcomponent code:
<template>
<div>
<div class="box">{
{
tran}}</div>
</div>
</template>
<script>
export default {
data(){
return{
}
},
props:["tran"]
}
</script>
2. Use this.$parent in the child component to receive the value of the parent component
Parent component code:
<template>
<div>
<Page1 :tran="msg"></Page1>
</div>
</template>
<script>
import Page1 from "./components4/Page1.vue"
export default {
data(){
return{
msg:"我是父组件传过来的值22"
}
},
components:{
Page1
}
}
</script>
Subcomponent code:
<template>
<div>
<div class="box">{
{
info}}</div>
</div>
</template>
<script>
export default {
data(){
return{
info:"1111"
}
},
mounted(){
//打印的是对象
console.log(this.$parent)
this.info=this.$parent.msg
}
}
</script>
3. Use this.$attrs for deep transfer
When we pass values in multiple layers, and the middle layer does not use the passed values, we can use this.$attrs.
Here is a demonstration of three layers of value passing:
Root component code:
<template>
<div>
<Page1 :tran="msg" :name="msg2"></Page1>
</div>
</template>
<script>
import Page1 from "./components4/Page1.vue"
export default {
data(){
return{
msg:"我是根组件传过来的值22",
msg2:"my name is Kangkang"
}
},
components:{
Page1
}
}
</script>
Middle layer code:
<template>
<div>
<PageSon v-bind="this.$attrs"></PageSon>
</div>
</template>
<script>
import PageSon from "./components/PageSon.vue";
export default {
data() {
return {
}
},
components:{
PageSon
}
}
</script>
Third level code:
<template>
<div>
{
{
this.$attrs}}
</div>
</template>
<script>
export default {
mounted(){
console.log(this.$attrs)
}
}
</script>