首页 > 解决方案 > 事件有效负载中的 Vue.js ReferenceError

问题描述

我有一个带有图像的用户个人资料页面。我正在将图像上传到 Firebase 存储,更新用户在 Firestore 中的记录以指向图像并显示它。我的所有东西都在一个组件中工作。

现在我想重构将图像上传功能放入它自己的组件中,新组件将返回上传文件的 url,以便父组件可以更新 Firestore。好处是我可以在其他页面上重复使用图片上传组件,而上传者不需要知道为什么要上传图片。我的架构方式如下:

<template>
...
<v-btn 
    :disabled="!file" 
    class="primary" 
    small 
    @click.prevent="selected">Upload</v-btn>

...
</template>
export default {
  name: "BaseImageUploader",
  props: {
    accept: {
      type: String,
      default: () => "image/png, image/jpeg, image/bmp"
    },
    placeholder: {
      type: String,
      default: () => "Click to select an image to upload"
    },
    label: {
      type: String,
      default: () => "Profile Picture"
    }
  },
  data: () => ({
    file: null
  }),
  methods: {
    selected() {
      const fileRef = storage.child("corporate-wellness-1/" + this.file.name);

      fileRef
        .put(this.file)
        .then(uploadTaskSnapshot => uploadTaskSnapshot.ref.getDownloadURL())
        .then(url => this.$root.$emit("base-image-uploader", url))

    }
  }
};

然后父级监听事件并像这样更新 Firestore:

...
mounted() {
    this.$root.$on(`base-image-uploader`, (event) => {
            this.uploadImage(event)
    });
},
...
uploadImage(url) {
    this.$store
        .dispatch("user/updateProfileImageUrl", url)
        .then(() => console.log('image url updated in bio'))
}

问题是我得到

ReferenceError: url is not defined

在父组件中的调度上。

该事件仅在 url 在子组件中可用后才会发出,所以我不明白为什么在调用事件处理程序时它在父组件中不可用。

所以,我有两个问题:

  1. 为什么编写的代码不起作用?
  2. 更一般地说,有没有更好的方法来构建它?

标签: vue.jsvue-component

解决方案


推荐阅读