vue.js - 如何监听在 vue js 中以编程方式创建的子事件?

标签 vue.js vuejs2

我有两个组件,一个是子组件,一个是父组件。

我正在手动实例化父级中的子级并手动安装它。

这是因为我的子组件是无渲染的,并且它没有像 <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();
  }

这是一个工作示例:https://codepen.io/gurupras/pen/qBNWbag

关于vue.js - 如何监听在 vue js 中以编程方式创建的子事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64209469/

相关文章:

vue.js - v-img : require ('../img/book.png' ) is a module and can't be loaded

vue.js - v-text-field textarea 默认高度变化?

vue.js - 通过名称和参数获取 vue-router 的路由

vue.js - Vuex - 将状态克隆到数据对象属性中,无法删除数组项

vue.js - 如何在开发模式下运行 `ionic build`?

javascript - 仅当输入值发生变化时才提交表单

javascript - 单击 Vuetify 按钮时如何重新加载页面?

javascript - Vue JS 数据对象在我的方法中不可用

javascript - Vue.js - 我该如何解决 [Vue 警告] : Error in render: "TypeError: Cannot read property ' port' of undefined"?

vuejs2 - Vue-Jest(Jest 单元测试): SyntaxError : Cannot use import statement outside a module