我遇到了一个问题,即从动态组件 (或)swap-components
发出的自定义事件 ( ) 在动态组件 ( ) 的父级中没有被正确收听。A.vue
B.vue
HelloWorld.vue
这是GitHub 上的源代码(使用 vue cli 3 创建)。
这是一个显示问题的现场演示。
在现场演示中,您将看到单击具有背景颜色的动态组件中的按钮不会更改动态组件。但是,当单击背景颜色下方的按钮(源自HelloWorld.vue
父级)时,动态组件确实发生了变化。
为什么会发生这种情况以及如何解决?
下面我将把感兴趣的 3 个主要文件的内容复制到这篇文章中:
HelloWorld.vue
(父母)A.vue
(动态组件中使用的子组件)B.vue
(动态组件中使用的子组件)
HelloWorld.vue
:
<template>
<div>
<h1>The dynamic components ⤵️</h1>
<component
:is="current"
v-bind="dynamicProps"
></component>
<button
@click="click"
>Click me to swap components from within the parent of the dynamic component</button>
</div>
</template>
<script>
import A from "./A.vue";
import B from "./B.vue";
export default {
data() {
return {
current: "A"
};
},
computed: {
dynamicProps() {
return this.current === "A" ? { data: 11 } : { color: "black" };
}
},
methods: {
click() {
this.$emit("swap-components");
},
swapComponents() {
this.current = this.current === "A" ? "B" : "A";
}
},
mounted() {
this.$nextTick(() => {
// Code that will run only after the
// entire view has been rendered
this.$on("swap-components", this.swapComponents);
});
},
components: {
A,
B
},
props: {
msg: String
}
};
</script>
A.vue
:
<template>
<section id="A">
<h1>Component A</h1>
<p>Data prop sent from parent: "{{ data }}"</p>
<button @click="click">Click me to swap components from within the dynamic component</button>
</section>
</template>
<script>
export default {
props: ["data"],
methods: {
click() {
this.$emit("swap-components");
}
}
};
</script>
B.vue
:
<template>
<section id="B">
<h1>Component B</h1>
<p>Color prop sent from parent: "{{ color }}"</p>
<button @click="click">Click me to swap components from within the dynamic component</button>
</section>
</template>
<script>
export default {
props: ["color"],
methods: {
click() {
this.$emit("swap-components");
}
}
};
</script>