我遇到了一个问题,动态组件(A.vue或B.vue)发出的自定义事件(B.vue)在动态组件(HelloWorld.vue)的父级中没有被正确地侦听。
下面是GitHub上的源 (使用vue cli 3创建)。
这是一个显示问题的现场演示。
在现场演示中,您将看到用背景色单击动态组件中的按钮不会改变动态组件。但是,当单击背景色下面的按钮(起源于HelloWorld.vue父级)时,动态组件确实会发生变化。
为什么会发生这种情况,以及如何解决?
下面我将把三个感兴趣的主要文件的内容复制到这篇文章中:
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>发布于 2018-12-29 03:24:53
我猜这是因为事件侦听器正在侦听由父组件本身发出的swap-components事件。也许您可以通过侦听子组件中的swap-components事件,然后在父组件上发出一个事件来修复这个问题。
<template>
<div>
<h1>The dynamic components ⤵️</h1>
<component
:is="current"
v-bind="dynamicProps"
@swap-components="$emit('swap-components')"
></component>
<button
@click="click"
>Click me to swap components from within the parent of the dynamic component</button>
</div>
</template>或者,当子组件发出事件时,可以直接调用您的方法。
<template>
<div>
<h1>The dynamic components ⤵️</h1>
<component
:is="current"
v-bind="dynamicProps"
@swap-components="swapComponents"
></component>
<button
@click="click"
>Click me to swap components from within the parent of the dynamic component</button>
</div>
</template>发布于 2018-12-29 03:19:03
当您使用函数时,this不再绑定到上下文。它仅限于功能范围。使用箭头函数使this绑定到父上下文。
更改:
this.$nextTick(function() {通过以下方式:
this.$nextTick(() => {https://stackoverflow.com/questions/53966375
复制相似问题