【问题标题】:How to respond to a promise resolved inside a Vue event handler如何响应在 Vue 事件处理程序中解决的承诺
【发布时间】:2021-01-24 11:15:10
【问题描述】:

给定以下组件

<template>
  <div class="text-center">
    <v-dialog
      v-model="dialog"
      width="500"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          color="red lighten-2"
          dark
          v-bind="attrs"
          v-on="on"
        >
          Click Me
        </v-btn>
      </template>

      <v-card>
        <v-card-title class="headline grey lighten-2">
          Privacy Policy
        </v-card-title>

        <v-card-text>
          Some text
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="primary"
            text
            @click="handleAsyncAction"
          >
            I accept
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

@Component()
export class MyDialog extends Vue {
 dialog: booolean = false;
 
  async handleAsyncAction() {
  const value = await this.$emit('click'); // you can't really do that
  if(value === 'x') {
    dialog = false; //<--- then close
  } else {
   alert('error!')
  }
 }
}
</script>

被一些家长这样使用:

<template>
 <div>
  <MyDialog @click="makeSomeAjaxRequest($event)"
 </div>
</template>

<script type="ts">
import Vue from "vue";
import Component from "vue-class-component";
import MyDialog from "./MyDialog"

@Component({
  components: { MyDialog }
})
export default class ParentComponent extends Vue {
  async makeSomeAjaxRequest() {
    const data = await fetch('http://example.com');
    return data.toString();
  }

}
</script>

使用 React,您将能够从父级传递一些函数并将整个事情包装起来,但据我了解,这不是 Vue 的做事方式。

我应该如何让子组件“等待”来回调用?

【问题讨论】:

    标签: javascript vue.js promise async-await


    【解决方案1】:

    Vue 将所有相关的事件侦听器存储在this.$listeners 下的组件内

    通过利用它,您将能够在不发出实际事件的情况下调用该函数:

    // MyDialog
    async handleAsyncAction() {
      //@ts-ignore since Vue 2s' TS definitions condone such behavior
      const value = await this.$listeners.click();
      if(value === 'x') {
        dialog = false; //<--- then close
      } else {
       alert('error!')
      }
     }
    }
    

    你可以在一篇名为Reacting to Promises from event listeners in Vue.js的文章中看到一个完整的例子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-13
      • 2021-04-10
      • 2022-01-22
      • 1970-01-01
      • 2015-03-24
      • 2020-11-17
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多