【问题标题】:vue.js - v-on:change is not listeningvue.js - v-on:change 没有在听
【发布时间】:2019-02-15 00:42:42
【问题描述】:

我正在使用 Vue.js 版本 2.5.17,最近 v-on:change 不再工作。

用户单击“选择文件”按钮,在此更改上应捕获图像名称。在此之后,它将触发文件或文件显示在屏幕上,然后保存到 firebase。

相反,我现在收到一个错误:

job.vue?d03e:825 Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
    at eval (job.vue?d03e:825)
    at new Promise (<anonymous>)
    at new F (_export.js?90cd:36)
    at VueComponent.uploadFile (job.vue?d03e:823)
    at VueComponent.uploadProofOfWork (job.vue?d03e:787)
    at click (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?{"id":"data-v-45a8035d","hasScoped":false,"optionsId":"0","buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/job.vue (0.491509201fd57af656ef.hot-update.js:7), <anonymous>:1096:55)
    at invoker (vue.esm.js?efeb:2027)
    at HTMLAnchorElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1826)

name 属性位于附加到 v-on:change 的 fileUploaded 函数中。

模板:

<!-- DISPLAY IMAGES -->
<div class="job-images">
    <div v-for="(img, index) in this.job.images" :key="index" class="job-image-block">
        <img :src="img.url" :alt="img.name" />
    </div>
</div>
<!-- REMOVE IMAGE BEFORE UPLOAD -->
<div v-for="(image, index) in images" :key="index">
    <a @click.prevent="removeImage(index)">X</a>
    <img :src="image.src" />
</div>
<!-- THE CHOOSE IMAGE BUTTON -->
<span class="input-group-text btn btn-primary btn-file" id="basic-addon2">
                        <input type="file" v-on:change="fileUploaded" accept="image/png, image/jpeg, image/gif"
                               name="input-file-preview" multiple/>
                      </span>
<div>
    <p>{{ loadingText }}</p>
</div>
<!-- UPLOAD IMAGE(S) BUTTON -->
<vue-button v-userRole.worker="{cb: uploadFile, role: job.role}" accent>
    <a @click.prevent="uploadProofOfWork()" style="color: white;">
                      {{ $t('App.job.uploadFileButton' /* Save Uploaded Images */) }}
                    </a>
</vue-button>

JS

uploadProofOfWork() {
        this.uploadFile().then(imageUrl => {
            this.data.image = imageUrl;
            db
                .collection("jobs")
                .where("taskId", "==", this.taskId)
                .add(this.data)
                .then(function(docRef) {
                    this.self.clearForm();
                    this.self.loadingText = this.$t(
                        "App.job.uploadedPhotoSuccessfully"
                    ) /* Post was created successfully. */ ;
                })
                .catch(function(error) {
                    console.error("Error adding document: ", error);
                });
        });
    },
    async uploadImages() {
        const self = this;
        const results = this.images.map(async({ file }) => {
        const imageUrl = await this.uploadFile(file, self.job.taskId);
        return { name: file.name, url: imageUrl };

        });
        Promise.all(results).then(async imageUrls => {
            if (!Reflect.has(this.job, "images")) this.job.images = [];
            const images = [...this.job.images, ...imageUrls];
            const result = await db
                .collection("jobs")
                .doc(this.job.taskId)
                .set({ images }, { merge: true })
                .then(docRef => {
                    console.log("updated!", docRef);
                });
        });
    },
    uploadFile(file, jobId) {
        return new Promise((resolve, reject) => {
            const self = this;
            const storageRef = firebaseStorage
                .ref()
                .child("jobs/" + jobId + "/" + file.name + "-" + uuid.v1());
            let uploadTask = storageRef.put(file);
            uploadTask.on(
                "state_changed",
                function(snapshot) {
                    const progress =
                        snapshot.bytesTransferred / snapshot.totalBytes * 100;
                    self.loadingText =
                        this.$t('App.job.uploadedPhotoProgress') /* Upload is */ +
                        progress +
                        this.$t(
                            'App.job.uploadedPhotoProgress2'
                        );
                    /* % done. Processing post. */
                    this.upload.progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
                    console.log(this.upload.progress);
                },
                function(error) {
                    reject(error);
                },
                async function() {
                    const downloadUrl = await uploadTask.snapshot.ref.getDownloadURL();
                    resolve(downloadUrl);
                }
            );
        });
    },
    async fileUploaded(e) {
        const images = await Promise.all(
            Array.from(e.target.files).map(file => {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = e => {
                        resolve({ src: e.target.result, file, progress: null });
                    };
                    if (e.target.file) {
                        reader.readAsDataURL(e.target.this.file[0]);
                    }
                });
            })
        );
        this.images = images;
        console.log(this.images);
    },

【问题讨论】:

  • 我不知道你如何使用 vue.js 3.0.1,因为最后一个版本是 2.5.17...你能把整个堆栈跟踪复制到这里吗(例如在哪一行抛出错误)?
  • @MátéWiszt,我已根据您的要求更新了帖子。我也明白你对版本的意思。我以为$vue --version 命令给出了最新版本,但它给出了 vuex 版本。我检查了package.json,看到vue版本实际上是"vue": "^2.5.17"
  • 错误与@change事件无关,请提供job.vue的内容
  • @boussadjrabrahim,上面贴的是job.vue的模板和js。
  • 但您只粘贴方法

标签: javascript vue.js vuejs2


【解决方案1】:

堆栈跟踪显示错误发生在uploadFile 中,由uploadProofOfWork 调用。错误是Cannot read property 'name' of undefined。在uploadFile 中对.name 的唯一引用是file.name,其中file 是一个函数参数。如果您查看uploadProofOfWork,则没有传递给uploadFile 的参数:

this.uploadFile().then(imageUrl => /* ... */)

您的代码似乎没有在uploadProofOfWork 路径中的任何位置定义file。我在fileUploaded 中看到了file,但似乎这些文件打算上传到uploadImages(而不是uploadProofOfWork)。也许您的代码缺少“工作证明”的单独文件输入。

【讨论】:

  • 你的意思是这样的吗:` this.uploadFile(file).then(imageUrl => {` 因为那行不通。
  • 我认为问题比我们想象的要简单得多:在 uploadProofOfWork 中,您调用了 uploadFile 但没有任何参数,尽管您使用两个参数定义了它:file 和 jobId
猜你喜欢
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 2018-03-06
  • 2019-11-08
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
相关资源
最近更新 更多