首页 > 解决方案 > Vue继续成功回调

问题描述

我有一个具有 Vuex 依赖项的 Vue 应用程序。程序逻辑是Facebook分享成功后发送消息。

这是在单击按钮以发送消息时触发的方法:

onSubmit() {
    if(this.shouldShowShareModal){
        this.$store.dispatch('openModal', 'SHARE_MODAL');
        return;
    }

    this.$store.dispatch('sendMessage', {
        conversation_id: this.conversationId,
        message        : this.messageText,
        message_type_id: 1
    }).then(() => {
        this.messageText = '';
        this.scrollToBottom();
    });
},

openModal只需将给定模态的值设置为 true,从而v-if显示具有在share方法上触发 Facebook 分享的按钮的模态:

share() {
    var self = this;
    FB.ui({
        method: 'share',
        href: 'https://developers.facebook.com/docs/'
    }, function(){
        self.$store.dispatch('sharedThroughFacebook');
        self.$store.dispatch('closeModal', 'SHARE_MODAL');
    });
}

现在我遇到的问题是 Facebook 回调成功后如何继续发送消息?目前,sharedThroughFacebook我只是将商店共享标志设置为 true,但我不确定仅在成功回调后发送消息的最佳方法?如果我将数据推送到模态,那似乎是一个肮脏的解决方案,并且模态不应该知道消息状态。另一方面,将对话 ID、消息、类型和文本放在 Vuex 存储中似乎是一种开销,因为该组件是唯一使用数据的组件。

标签: javascriptvuejs2vuex

解决方案


你可以像这样组成你的动作

actions: {
  async share ({ dispatch, commit }) {
    await dispatch('sharedThroughFacebook') // wait for `sharedThroughFacebook` to finish
    await dispatch('closeModal') // close the modal before sending the message
    commit('sendMesseage') 
  },
  async sharedThroughFacebook (context, payload) {
     FB.ui({
        method: 'share',
        href: 'https://developers.facebook.com/docs/'
    })
 }
}

推荐阅读