javascript - 如何在 .vue 文件的 <script> 部分的父组件中处理通过 this.$emit 发出的自定义子事件?

标签 javascript typescript vue.js vuejs2

我们使用 vue 和 typescript,因此我们的 .vue 文件的组织方式与 this blogpost. 基本相同。

我有一个发出自定义事件的子组件 changeType 。我想在发出此事件时调用父组件上的函数。

childComponent.vue

<template>
  <div>
    <span @click="changeType('test')"></span>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class ChildComponent extends Vue {
  @Prop(
    {
      default: 'notTest',
      validator: (type) => {
        return [
          'test',
          'notTest',
        ].indexOf(type) > -1;
      },
    },
  )
  currentType!: string;

  changeType(currentType = 'notTest') {
    this.$emit('changeType', currentType);
  }
}
</script>

现在,我不确定要在我的 parentComponent.vue 文件中放入什么内容,该文件具有 <childComponent />在其 template面积。

Vue documentation仅解决 <template> 内子事件的处理文件区域,使用 v-on :

<blog-post
  ...
  v-on:enlarge-text="postFontSize += 0.1"
></blog-post>

所以,我想,我是否需要这样的东西:

parentComponent.vue

<template>
  <childComponent v-on:changeType="handleChangeType" />
</template>

或者有什么方法可以在 <script> 中做到这一点仅标记区域?使用类+ typescript 语法使研究变得更加困难。我正在尝试诸如 this.$on 这样的事情但 typescript 根本不喜欢这样,或者我可能把它放在类的错误部分(也许它属于构造函数或类似的部分?)

我有 Backbone 背景,所以我希望有类似 onChangeType 的东西。直接添加到父组件的方法将自动处理该事件,尽管这可能是老派,并且有更新的更好的方法。

如何在 vue 中处理父组件标签内的子组件事件? 没有 v-on 是否可以?在模板内?我是否误解了执行此操作的“正确”方法?

最佳答案

您可以通过$on method向子组件添加事件监听器,你提到过。

首先,您需要向模板中的子组件添加 ref:

<childComponent ref="child"/>

然后,在 mounted Hook 中,您将添加监听器,如下所示:

mounted() {
  this.$refs.child.$on('changeType', this.handleChangeType);
}

关于javascript - 如何在 .vue 文件的 &lt;script&gt; 部分的父组件中处理通过 this.$emit 发出的自定义子事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467982/

相关文章:

javascript - 如何将所有行读入第三级 jqgrid/subGrid。请看图片

javascript - Angular.js - Google 自动完成事件触发时清除文本框?

javascript - 如何在单击按钮时验证输入不保存 0 或小于 0?

angular - ionic 3 可排序网格或表格

javascript - PhpStorm 中预期的表达式

vue.js - Nuxt.js/Vuex - 在 mapActions 助手中使用命名空间模块,[vuex] 未知操作类型 : FETCH_LABEL

javascript - 如何在 JQuery 中的 foreach 中包含 foreach?

javascript - 浏览器不显示文件已下载

javascript - Chrome : use sourcemaps to debug contentscript

javascript - 我使用 Vue js 和 python Flask 作为后端。我想要设置一些局部变量。如何做呢?