【问题标题】:VueJS how to listen to event from method not from templateVueJS如何从方法而不是模板监听事件
【发布时间】:2017-08-22 21:04:53
【问题描述】:

我正在从子组件向其父组件发送事件。我想通过父级中的方法拦截信号。但是无论是否发出事件,监听函数都会触发。请注意,我使用的是单文件组件和 Vue-router。

顺便说一句,我发现很少有 VueJS 示例使用单文件组件,对于菜鸟来说,从一个文件中的简单 Vue 应用程序转换为多个单文件组件可能会令人困惑。

家长:

<template>
 ....html here
</template>
<script>
  import Child from './Child.vue'

  export default {
  name: 'Parent',
  data () {
    return {
     stage: 1
    }
  },
  components: {
    Child
  },
  created: function () {
    // the following line always runs even when listen for non-existent event eg this.$on('nonsense'...)
    this.$on('child-event', this.stage = 2)
  }
  }

孩子:

<template>
  <button v-on:click="sendEvent" type="button" class="btn btn-success">Next</button>
</template>

<script>
  export default {
  name: 'Child',
  data () {
    return {
      response_status: 'accepted'
    }
  },
  methods: {
    sendEvent: function () {
      this.$emit('child-event', 'accepted')
    }
  }

知道我做错了什么吗?

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

另一种设置on 事件的方法是直接从您调用子组件的位置引用侦听器方法。

在您的父模板上,您可以执行以下操作:

<Child v-on:child-event="eventIsEmitted"></Child>

在你的methods

eventIsEmitted: function(status) {
    if (status == 'accepted') {
        this.stage = 2;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2018-09-10
    • 2020-05-07
    • 2023-03-07
    • 2014-07-27
    • 2011-09-30
    • 2019-09-06
    相关资源
    最近更新 更多