等待祖父组件的方法在孙子组件中解析

Await a grandparent component's method to be resolved in grandchild component

我的 vue 应用程序中有三个组件:

Home 组件有一个异步方法:

async handleDialogAccept() {
  try {
    const response = await this.$axios.get('https://jsonplaceholder.typicode.com/todos/');
    console.log(response.data);
  } catch (err) {
    console.log(err);
  }
},

它会在 Dialog 组件发出 "accept" 自定义事件后立即执行:

<dialog-confirmation
  @accept="handleDialogAccept()"
/>

Dialog 组件有一个 child (Button):

<button-accept
  v-on="$listeners"
>
  Accept
</button-accept>

在我的 buttonAccept.vue 中,它被导入 Dialog 并如上所示使用,具有下一个结构:

<template>
  <v-btn
    color="primary"
    @click="handleClick()"
    :loading="loading"
    :disabled="loading"
  >
    <slot name="accept"></slot>
  </v-btn>
</template>

<script>
export default {
  props: ['parentFunction'],
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    handleClick() {
      this.$emit('accept');
    },
  },
};
</script>

我想在 handleClick 方法中执行后续步骤:

  1. loading 设为真
  2. 发出接受自定义事件
  3. 等到handleDialogAccept完成
  4. loading 设置为 false

需要等待吗?

或许,你可以在Home组件中定义一个变量(isAcceptDone)来判断Button组件中async方法是否完成。

Home 组件

async handleDialogAccept() {
  try {
    const response = await this.$axios.get('https://jsonplaceholder.typicode.com/todos/');
    console.log(response.data);
    this.isAcceptDone = true;
  } catch (err) {
    console.log(err);
  }
},

Dialog 组件

<dialog-confirmation
  @accept="handleDialogAccept()"
  :isAcceptDone="isAcceptDone"
/>

Button 组件

<script>
  export default {
    props: ['parentFunction', 'isAcceptDone'],
    data() {
      return {
        loading: false,
      };
    },
    watch: {
      isAcceptDone(val) {
         if(val) {
           this.loading = false
         }
      }
    },
    methods: {
      handleClick() {
        this.$emit('accept');
      },
    }
 };
</script>

另一方面,如果您认为在三个组件中传递 isAcceptDone 太复杂了。使用 EventBus 是另一种简单的方法。