【问题标题】:Vue.js Emit event from ServiceVue.js 从服务发出事件
【发布时间】:2019-02-05 19:16:46
【问题描述】:

我想知道如何从 .js 文件(提供文件上传服务的类)向组件发出事件。我的想法是为进度 UI 元素发出四个事件。

我的服务 .js 文件是这样的:

import Vue from 'vue';

export const UploaderService = new Vue({
 methods: {
    orchestrateDataPublication() {
        return new Promise((resolve, reject) => {
            if (this.checkRequiredData()) {
                // emit 25% done
                this._getSignedUrl().then(signedUrlResponse => {
                 // emit 50% done
              this._uploadDataset(signedUrlResponse).then(uploadResponse => {

等等。

这是在 Vue 组件中导入的:

<script>
import {UploaderService} from '../service/uploaderService.js'
export default {
        upload () {
        this.$refs['datasetForm'].validate((valid) => {
            if (valid) {
                UploaderService.orchestrateDataPublication().then((response) => {
                    this.$emit(response.type, response.data)
                }, (err) => {
                    this.$emit(err.type, err.data)
                })
            } else {
                this.$emit('appInforms', ' -PLEASE, check all your inputs- ')
            }
        })
    }

这里上传使用 orchestrateDataPublication 作为承诺,但我需要以某种方式发出事件。这可能吗?

【问题讨论】:

  • 看看event bus。这基本上是与您的主应用程序分开的 Vue 实例,您可以在其上发出和监听事件。

标签: javascript vue.js ecmascript-6 vuejs2 vue-component


【解决方案1】:

由于UploaderService 本身是一个Vue 实例,您可以使用它的$on 方法来监听事件,并使用$emit 方法来调度事件。上传完成后,您可以使用$off 停止监听进度事件。

upload() 中,为我们称为“progress”的事件设置一个事件监听器,然后调用UploaderService.orchestrateDataPublication(),并在其then 回调中停止监听progress 事件:

upload() {
  UploaderService.$on('progress', progress => console.log({ progress }));

  UploaderService.orchestrateDataPublication().then(message => {
    console.log({ message });
    UploaderService.$off('progress');
  });
}

UploaderService.orchestrateDataPublication() 中,发出这样的进度事件:

this.$emit('progress', 0.75); // 75% complete

demo

注意:如果您的项目允许 ES2017,您可以使用 async/await 来缓解您的回调嵌套,如 codesandbox 所示。

【讨论】:

  • 你先生救了我的命
  • 谢谢!如果组件不扩展 Vue,是否有替代方案,或者只是建议将所有东西都变成 Vue 组件?
  • 谢谢!我最终使用了基于 Vue 的事件总线模式来处理服务事件 (alligator.io/vuejs/global-event-bus)。
猜你喜欢
  • 2017-04-01
  • 2020-10-07
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多