我想知道如何从 .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 作为 promise ,但我需要以某种方式发出事件。这可能吗?
最佳答案
因为 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
来减少回调嵌套,如 codesandbox 所示.
关于javascript - Vue.js 从服务发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52103882/