$attrs父组件可以将数据传给内部组件。
用了就没了(上个组件用了,此数据就不会传到下一个组件)
我定义了四个组件(包含关系如下)
FatherDom.vue
<template>
<div>
<son-dom :coo="coo" :foo="foo" :doo="doo" />
</div>
</template>
<script>
import SonDom from "@/components/SonDom.vue";
export default {
components: { SonDom },
name: "FatherDom",
data() {
return {
coo: "你是一只快乐的小咸鱼",
foo: "我不是一只小咸鱼,你才是",
doo: "吃瓜吃瓜",
};
},
methods: {},
};
</script>
SonDom.vue
<template>
<div>
<son-child v-bind="$attrs" />
</div>
</template>
<script>
import SonChild from "./SonChild.vue";
export default {
components: { SonChild },
created() {
console.log("SonDom", this.$attrs);
},
};
</script>
SonChild.vue
<template>
<div>
<child-child v-bind="$attrs" />
</div>
</template>
<script>
import ChildChild from "./ChildChild.vue";
export default {
components: { ChildChild },
props: ["doo"],
inheritAttrs: false,
name: "SonChild",
created() {
console.log("SonChild", this.$attrs);
},
};
</script>
ChildChild.vue
<template>
<div>
</div>
</template>
<script>
export default {
name: "ChildChild",
created() {
console.log("ChildChild", this.$attrs);
},
};
</script>
$listeners使用(接收父组件传递的方法)
FatherDom.vue
<template>
<div>
<son-dom v-on="{change}" />
</div>
</template>
<script>
import SonDom from "@/components/SonDom.vue";
export default {
components: { SonDom },
name: "FatherDom",
data() {
return {};
},
methods: {
change() {
console.log(111);
},
},
};
</script>
SonDom.vue
<template>
<div>
<son-child v-on="$listeners" />
</div>
</template>
<script>
import SonChild from "./SonChild.vue";
export default {
components: { SonChild },
created() {
console.log("SonDom", this.$listeners);
},
};
</script>
SonChild.vue
<template>
<div>
<child-child v-on="$listeners" @changeDom="changeDom" />
</div>
</template>
<script>
import ChildChild from "./ChildChild.vue";
export default {
components: { ChildChild },
props: ["doo"],
inheritAttrs: false,
name: "SonChild",
methods: {
changeDom() {
console.log(222);
},
},
created() {
console.log("SonChild", this.$listeners);
},
};
</script>
ChildChild.vue
<template>
<div>
</div>
</template>
<script>
export default {
name: "ChildChild",
created() {
console.log("ChildChild", this.$listeners);
},
};
</script>
父向子传递函数。子向父传递函数,写法相似, 不过需要$emit