【问题标题】:Event Listening from Child to Parent in VuejsVuejs 中从子级到父级的事件监听
【发布时间】:2018-10-21 17:34:35
【问题描述】:

我想从子组件向其父组件发送一个事件,这应该会改变视图。

我能够创建事件并发出它,但是我的模板似乎没有注册它,我使用的是单文件组件 (SFC)。此外,如果我手动更新数据对象一切正常。

App.vue(父级)

<template>
    <div v-on:change-view="updateView">
        <!-- render the currently active component/page here -->
        <component v-bind:is="currentView"></component>
    </div>
</template>
<script>
export default {
  name : 'app',
  data () {
      return {
          currentView : 'Modal'
      }
  },
  methods : {
      updateView (view) {
          console.log('event listener!!!')
          this.currentView = view;
      }
  }
}
</script>

Modal.vue(子)

<template>
    <div> 
        <vk-modal v-bind:show="show">
            <h1>{{ title }}</h1>
            <p>{{ body }}</p>
            <p class="uk-text-right">
                <vk-button v-on:click="$emit('change-view', 'Purposes')">More Information</vk-button>
                <vk-button v-on:click="fullConsent" type="primary">I Agree</vk-button>
            </p>
        </vk-modal> 
    </div>
</template>
<script>
export default {
  name : 'modal',
  data () {
      return {
          show : true,
          title : 'Hello'
      }
  },
  methods : {
        fullConsent () {
            this.show = false;
        }
  }
}
</script>

请帮忙:)

【问题讨论】:

  • App.vue 中是否提供Purposes 组件,即注册为全局组件?否则必须注册为本地组件。
  • 我在 main.js 中调用 Vue.component('Purposes', Purposes);

标签: javascript vue.js vuejs2 frontend


【解决方案1】:

你需要在&lt;component&gt;本身上注册事件监听器;组件事件不会冒泡 (unlike DOM events)。

<div>
    <component v-bind:is="currentView" v-on:change-view="updateView"></component>
</div>

【讨论】:

  • 是否还有一种方法可以通过 JS(方法)本身来做到这一点,既可以创建事件又可以监听?
  • 如果你有一个组件的引用(通过ref),那么你可以用$on添加一个监听器,见Programmatic Event Listeners
猜你喜欢
  • 2015-03-10
  • 2017-08-16
  • 2019-11-21
  • 2018-11-04
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多