【问题标题】:Parent comp. is not listening to child $emit父补偿。没有在听孩子 $emit
【发布时间】:2020-01-22 01:32:04
【问题描述】:

我创建了一个表单组件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>


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

子组件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 扩展中触发的事件:

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

【问题讨论】:

    标签: javascript vue.js events vuejs2 emit


    【解决方案1】:

    首先要做的事情。 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 并改用类进行样式设置。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 2021-06-18
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多