【问题标题】:Migrating to Vue 2.0 $on() is not hearing $emit()迁移到 Vue 2.0 $on() 没有听到 $emit()
【发布时间】:2017-01-12 04:16:17
【问题描述】:

背景:我正在从 1.0 迁移到 2.0。

目前,我正在使用嵌套组件。父母和孩子之间的关系非常好。但是,父组件和主 Vue() 实例之间的关系被打破了。在 Vue() 实例内的计算属性 cssstyle 中,不会像我预期的那样根据 $emit()/$on() 进行更新。

相关部分:

HTML中父组件的使用:

<f9-padding v-if="editable" ></f9-padding>

父组件内部

computed: {
    cssstyle: function() {
        var padding_style = this.padding();
        bus.$emit('padding_changed', padding_style);
        return padding_style;
    }
}

主 Vue() 实例内部

computed: {
    cssstyle: function() {
        console.log('cssstyle computed');
        bus.$on('padding_changed', function (padding_style) {
            return padding_style;
        });
        return 'padding: 0px;';
    },
    ...

父级中的计算属性更新得很好。然而,主 Vue() 实例内部的计算属性仅在页面加载时运行。我不明白如何从不使用 <input> 元素的父级发出数据。我在网站上找到的大多数示例都只关注<input> 案例。我刚刚计算的属性数据发生了变化。我尝试使用这里显示的方法:http://rc.vuejs.org/guide/components.html#Custom-Events,但我对这个文档的担心是它谈论的是组件之间的事件侦听,而不是父组件和主 Vue() 实例。

更新:我能够通过将父级上的计算属性更改为以下内容来解决此问题:

computed: {
    cssstyle: function() {
        var padding_style = this.padding();
        this.$root.cssstyle = padding_style;
        return padding_style;
    }
}

并将 cssstyle 从计算数据移动到根 Vue() 实例中的数据。

data: {
    cssstyle: 'padding: 0px;',
},

但是,我觉得使用起来有点脏:

this.$root.cssstyle

没有别的办法吗?

【问题讨论】:

  • 第一种方法应该可行。
  • 在根 Vue 实例上计算的 cssstyle 不会被 padding_changed 事件触发。

标签: javascript vue.js vuejs2


【解决方案1】:

对于事件发射和监听,请在 2.0 docs 中检查。

如果你从custom-component 发出this

cssstyle: function () {
  /*...*/
  this.$emit('onsomething', params)
}

然后,无论你在哪里创建这个组件的实例,你都可以这样做

<tamplate>
    <custom-component @onsomething="action"></custom-component>
</tamplate>

然后在你的 JS 中:

methods: {
  action: function (params) {
    console.log('On something')
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 1970-01-01
    • 2020-04-29
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多