首页 > 解决方案 > 父补偿。没有在听孩子 $emit

问题描述

我创建了一个表单组件Form.vue,它是PostPage.vue. 在“Form.vue”中,我想为父级发送 $emit 以更改 Prop 值btn-text

父组件PostPage.vue

<template>
  <div id="post-page">
    <div class="header-text pt-5 text-center">
      <div class="h2 font-weight-bold">
        Welcome to the DevTribe Community
      </div>
      <div class="h5 font-weight-bold">
        Ask questions, share content, introduce yourself. Be nice!
      </div>
    </div>
    <Form />
    <!-- textarea-not-clear isn't catched here below -->
    <Posts
      :btn-text="btnText"
      @textarea-not-clear="changeBtnText()"
    />
  </div>
</template>

<script>
import Form from './PostPage/Form.vue';
import Posts from './PostPage/Posts.vue';
export default {
  name: 'PostPage',
  components: {
    Form,
    Posts
  },
  data() {
    return {

    }
  },
  methods: {
    changeBtnText() {
      console.log('tss');
    }
  }
}
</script>

<style lang="scss" scoped>
#post-page {
    background-color: #ffffff;
    height: 100%;
    padding: 0 20%;

}
</style>


watch如果 textarea 为空,则发射将在 a 中触发

子组件Form.vue

<template>
  <div id="form">
    <form class="text-area text-center mt-5 mx-auto w-100">
      <div class="row">
        <div class="col-12">
          <textarea
            v-model="textarea"
            name="post-text"
            rows="6"
            class="w-100"
            placeholder="Create a post..."
          />
        </div>
        <div class="col text-left">
          <button
            type="button"
            class="btn btn-outline-primary"
          >
            Send
          </button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'Form',
  data() {
    return {
      textarea: ''

    }
  },
  watch: {
    textarea: function() {
      if (this.textarea !== '') {
        this.$emit('textarea-not-clear', 'Join Discussion');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.text-area {
    height: 300px;
    textarea {
        border: solid black 1px;
    }
    button {
        width: 120px;
    }
}
</style>


我可以看到在 DevTool 的 Vue 扩展中触发的事件: 在此处输入图像描述

但由于某种原因,无法捕获该事件,changeBtnText()内部的函数PostPage.vue不会被触发,甚至没有给出console.log('test')

标签: javascriptvue.jseventsvuejs2emit

解决方案


第一件事。Form不是一个好名称的组件,因为它与标准 HTML 元素冲突。我很惊讶您没有收到有关此的警告。见https://vuejs.org/v2/style-guide/#Multi-word-component-names-essential

接下来,您的事件的问题是您正在收听错误的组件。

<Form />
<!-- textarea-not-clear isn't catched here below -->
<Posts
  :btn-text="btnText"
  @textarea-not-clear="changeBtnText()"
/>

该事件正在由Form组件触发,但您的侦听器位于Posts组件上。

我还强烈建议您停止在组件上使用 id 并改用类进行样式设置。


推荐阅读