我有两个组件,一个是子组件,一个是父组件。
我正在手动实例化父级中的子级并手动安装它。
这是因为我的子组件是无渲染的,并且它没有像 <app-child></app-child>
这样的标签我可以用它在模板中实例化。
请注意,这里我没有像 VUE 中那样以常规方式绑定(bind) Prop 并监听事件 - 模板绑定(bind)和监听
在这里,我不会对模板进行任何处理。
所以我必须传递 Prop 并监听事件,如下所示。
但问题是,即使我从子级发出事件并在父级内部监听它。我没有看到任何迹象。
我以为我正在监听父级中的子事件,如下所示...我没有从该事件中得到任何响应。
这是父级
import { Child } from "./components/child";
import store from "@/store";
export default {
name: "parent",
components: {},
props: [],
data() {
return {
child: null,
};
},
computed: {},
created() {
this.child = new Child({
store,
parent: this,
propsData: {
item: 'one' /// I'm being able to pass props and receive them in the child component
},
}).$mount();
this.child.$on("hello", (e) => console.log(e, "yes")); // this is not working.
},
mounted() {
},
methods: {},
};
这是子发射事件...'hello'
import Vue from "vue";
const CHILD = {
name: "child",
components: {},
props: ["item"],
data() {
return {};
},
render() {
return null;
},
computed: {},
created() {
},
mounted() {
this.$emit('hello', 'parent') /// this is child emitting event. this should be caught by the parent..
},
methods: {},
};
export const Child = Vue.extend(CHILD);
如何解决这个问题?
最佳答案
事件正在按预期触发。问题是您错过了该事件,因为您在事件已经触发之后注册了监听器。
尝试按如下方式更改父组件:
created() {
this.child = new Child({
store,
parent: this,
propsData: {
item: 'one' /// I'm being able to pass props and receive them in the child component
},
})
this.child.$on("hello", (e) => console.log(e, "yes")); // Set up listener before event will be fired
this.child.$mount();
}
关于vue.js - 如何监听在 vue js 中以编程方式创建的子事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64209469/