[英]Vue.js Emit event from Service
我想知道如何从 .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 作为承诺,但我需要以某种方式发出事件。 这可能吗?
由于UploaderService
本身就是一个Vue
实例,你可以使用它的$on
方法来监听事件,并使用$emit
方法来调度事件。 上传完成后,您可以使用$off
停止侦听进度事件。
在upload()
中,为我们将称为“progress”的事件设置一个事件侦听器,然后调用UploaderService.orchestrateDataPublication()
,并在其then
回调中停止侦听进度事件:
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
注意:如果您的项目允许 ES2017,您可以使用async
/ await
来缓解您的回调嵌套,如代码框所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.