父组件传值给子组件:
1.父组件中自定义属性,子组件用props接收。
父组件代码:
<template>
<div>
<Page1 :tran="info"></Page1>
</div>
</template>
<script>
import Page1 from "./components4/Page1.vue"
export default {
data(){
return{
info:"我是父组件传过来的值"
}
},
components:{
Page1
}
}
子组件代码:
<template>
<div>
<div class="box">{
{
tran}}</div>
</div>
</template>
<script>
export default {
data(){
return{
}
},
props:["tran"]
}
</script>
2.子组件中用this.$parent接收父组件的值
父组件代码:
<template>
<div>
<Page1 :tran="msg"></Page1>
</div>
</template>
<script>
import Page1 from "./components4/Page1.vue"
export default {
data(){
return{
msg:"我是父组件传过来的值22"
}
},
components:{
Page1
}
}
</script>
子组件代码:
<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.使用this.$attrs进行深传递
当我们进行多层传值的时候,且中间层不使用传下来的值,可以使用 this.$attrs
此处演示三层传值:
根组件代码:
<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>
中间层代码:
<template>
<div>
<PageSon v-bind="this.$attrs"></PageSon>
</div>
</template>
<script>
import PageSon from "./components/PageSon.vue";
export default {
data() {
return {
}
},
components:{
PageSon
}
}
</script>
第三层代码:
<template>
<div>
{
{
this.$attrs}}
</div>
</template>
<script>
export default {
mounted(){
console.log(this.$attrs)
}
}
</script>