gpt4 book ai didi

javascript - 范围问题 - 在子实例中的 $emit 事件后未定义注入(inject)的父类

转载 作者:行者123 更新时间:2023-12-03 06:45:36 24 4
gpt4 key购买 nike

  • 我将 Vue 事件绑定(bind)到父类,然后将该类注入(inject)子类,然后将其注入(inject)子类。
  • 父事件可以正常工作,即父、子和子。

  • 问题

    如果我在子类中触发事件,子类将接收该事件,但子类已成为 Vue 实例,这意味着如果我运行它,我将得到 Vue 实例。我认为这就是我绑定(bind) child 事件的方式。

    JS Fiddle Example

    var vue = new Vue();

    var events = {
    fire: function(event, data = null){
    vue.$emit(event, data);
    },
    listen: function(event,callback){
    vue.$on(event, callback);
    },
    };


    class Parent {
    constructor(options) {
    this.options = options;
    }
    }

    // IMPORTANT - We bind the events to the parent class
    Object.assign(Parent.prototype, events);


    class Children {
    // We bind the events to the parent class
    constructor(parent) {
    this.parent = parent;
    this.children = [];

    const events = {
    REMOVE_CHILD: this.removeChild,
    CHILD_ADDED: this.childAdded,
    CHILD_REMOVED: this.childRemoved,
    };

    // we set the events using parent instance
    _.forEach(events, (a, k) => {
    this.parent.listen(k, a);
    });

    // we add first child
    this.addChild({name:'First Child'})
    }

    addChild(child) {
    var newChild = new Child(this.parent,child);
    this.children.push(newChild);
    //console.log('------- child added ', this);
    this.parent.fire('CHILD_ADDED', newChild);
    }

    removeChild(child) {
    // This works We get the child
    console.log('------- remove this child', child);
    // this.children = _.filter(this.children, (c) => c.id !== child.id);

    // We get an undefined
    console.log('------- PROBLEM - this parent is undefined', this.parent);

    // This fails as the instance is Vue from events
    this.parent.fire('CHILD_REMOVED', child);
    }

    allTheChildren() {
    return this.children;
    }

    childAdded(child) {
    console.log('------- child added', child);
    }
    }

    class Child {
    constructor(parent,child) {
    this.parent = parent;
    this.child = child;
    this.name = child.name;

    console.log('------- child class', this);
    }

    removeChild() {
    this.parent.fire('REMOVE_CHILD', this.child);
    }
    }

    var app = new Vue({
    el: "#app",
    data: {
    children: {},
    service: new Children(new Parent({}))
    },
    computed: {
    getChildren() {
    return this.children;
    },
    },
    mounted() {
    // example
    this.children = this.service.allTheChildren();
    }
    })


    最佳答案

    或者,您可以这样做:

    _.forEach(events, (f, k) => {
    this.parent.listen(k, f.bind(this));
    });

    关于javascript - 范围问题 - 在子实例中的 $emit 事件后未定义注入(inject)的父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60716510/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com