【问题标题】:Parent component not receiving child event in vue父组件在vue中没有收到子事件
【发布时间】:2020-04-19 02:30:40
【问题描述】:

我遇到了一个问题,即触发了一个事件,但父级似乎无法听到它。我已经烧了3个多小时试图找到问题无济于事。 这是父组件。

Thread.vue

    <script>
    import Tagging from '../components/Tagging.vue';

    export default {
        props: ['thread'],

        components: {Tagging},

        data () {
            return {
                repliesCount: this.thread.replies_count,
                locked: this.thread.locked,
                title: this.thread.title,
                body: this.thread.body,
                selectedTags: this.thread.selected_tags,
                form: {},
                editing: false
            };
        },
        methods: {
            tagsChanged(value){ <---- this handler is never called
                console.log("received")
            }
        }

    }
</script>

还有子组件

Tagging.vue

    <!-- Vue component -->
    <template>
     <div>
    <label class="typo__label">Tagging:</label>
    <multiselect
      v-model="value"
      tag-placeholder="Add this as new tag"
      placeholder="Search or add a tag"
      label="name"
      track-by="code"
      :options="options"
      :multiple="true"
      :taggable="true"
      @tag="addTag"
      @input="emitToParent" //this event handler emits an event to parent
    ></multiselect>
    </div>
   </template>

   <script>
     import Multiselect from "vue-multiselect";

export default {
  props: ["tags","previousTags","repliesCount"],
  components: {
    Multiselect
  },
  data() {
    return {
      value: this.previousTags,
      options: this.tags,
    };
  },
  methods: {
    addTag(newTag) {
      const tag = {
        name: newTag,
        code: newTag.substring(0, 2) + Math.floor(Math.random() * 10000000)
      };
      this.options.push(tag);
      this.previousTags.push(tag);
      this.form.selected_tags.push(tag)
    },
    emitToParent (event) {
      this.$emit('childToParent', this.value)//this event is being fired(verified on vue developer tools
    }
  }
};
</script>

在我的 HTML 上是模板

<tagging @childToParent="tagsChanged" :tags="some json" :previous-tags="some json"></tagging>

我尝试过改变

@childToParent="tagsChanged"

v-on:childToParent="tagsChanged"

但它不起作用。

我错过了什么?

谢谢

【问题讨论】:

  • 请在Thread.vue 组件中分享您的模板,了解您如何使用您的子组件。

标签: vue.js vuejs2 vue-component


【解决方案1】:

从表面上看,$emit 部分看起来不错。

首先,您能否将console.log() 添加到emitToParent 以确保您正在触发此方法。

其次,确保你没有收到任何错误,检查控制台。

第三,这是不正确的语法::tags="some json" :previous-tags="some json"。这会引发错误。

【讨论】:

  • 控制台没有错误,只是不会调用处理程序方法。 emitToParent 记录一条消息,并且该事件在 Vue 构建工具上也可见。这:``` :tags="some json" :previous-tags="some json" ``` 为了简洁起见,我只是剥离了一些代码。
猜你喜欢
  • 1970-01-01
  • 2017-07-07
  • 2020-03-18
  • 1970-01-01
  • 2019-11-12
  • 2020-10-02
  • 2018-06-23
  • 2019-02-20
  • 2021-07-26
相关资源
最近更新 更多