1、props 父组件向子组件、孙组件传递数据,$emit子组件向父组件发送消息,v-on:或是@父组件监听消息。
父组件
<template>
<div id="app">
<Child1
:pChild1="1111"
:p-child2="22222"
@test1="onTest1"
@test2="onTest2"
title="题目"
>
</Child1>
</div>
</template>
<script>
import Child1 from "@/views/Child1.vue";
export default {
data() {
return {};
},
components: { Child1 },
methods: {
onTest1() {
console.log("test1 running...");
},
onTest2() {
console.log("test2 running");
},
},
};
</script>
子组件
<template>
<div class="child-1">
<p>in child1:</p>
<p>props: {{ pChild1 }}</p>
<hr />
<Child2 @test2="test1" :pChild2="pChild1"></Child2>
</div>
</template>
<script>
import Child2 from "./Child2.vue";
export default {
props: ["pChild1"],
data() {
return {};
},
components: { Child2 },
mounted() {
this.$emit("test1");
},
methods: {
test1() {
this.$emit("test2");
},
},
};
</script>
孙组件
<template>
<div class="child-2">
<p>in child2:</p>
<p>props: {{ pChild2 }}</p>
<hr />
</div>
</template>
<script>
export default {
props: ["pChild2"],
data() {
return {};
},
mounted() {
this.$emit("test2");
},
};
</script>
2、$attrs 父组件向子组件、孙组件传递数据及方法调用。
$attrs 可以传递数据及方法
<template>
<div id="app">
<Child1
:pChild1="1111"
:p-child2="22222"
v-on:test1="onTest1"
v-on:test2="onTest2"
title="题目"
>
</Child1>
</div>
</template>
<script>
import Child1 from "@/views/Child1.vue";
export default {
data() {
return {};
},
components: { Child1 },
methods: {
onTest1() {
console.log("test1 running...");
},
onTest2() {
console.log("test2 running");
},
},
};
</script>
子组件
<template>
<div class="child-1">
<p>in child1:</p>
<p v-bind="$attrs">$attrs: {{ $attrs }}</p>
<!-- 结果: $attrs: { "pChild1": 1111, "p-child2": 22222, "title": "题目" } -->
<hr />
<Child2 v-bind="$attrs"></Child2>
</div>
</template>
<script>
import Child2 from "./Child2.vue";
export default {
data() {
return {};
},
inheritAttrs: true,
components: { Child2 },
mounted() {
this.$emit("test1");
}
};
</script>
孙组件
<template>
<div class="child-2">
<p>in child2:</p>
<p>$attrs: {{ $attrs }}</p>
<!-- 结果: $attrs: { "pChild1": 1111, "p-child2": 22222, "title": "题目" } -->
<hr />
</div>
</template>
<script>
export default {
data() {
return {};
},
inheritAttrs: false,
mounted() {
this.$emit("test2");
},
};
</script>
注:
1、若一个组件内同时含有props
a
t
t
r
s
,
则
attrs ,则
attrs,则attrs传递除props剩余内容;
2、inheritAttrs:true根元素继承属性 false指定元素
如果你不希望组件的根元素继承特性,你可以在组件的选项中设置 inheritAttrs: false。