【问题标题】:How to dynamically change vuejs Method based on route parameters?如何根据路由参数动态改变vuejs方法?
【发布时间】:2021-02-25 00:25:17
【问题描述】:

我构建了一个可重复使用的组件,用户可以在其中上传图像并将其存储在 firebase 存储中。问题是我的组件需要能够使用与正在更新的部分协调的标签来引用数据库中的图像。

当我为“downloadURL”命名位置时,我的问题出在我的方法上。在下面的代码中,我创建了变量“picName”并将其定义为部分名称,后跟“imgUrl”。但是,当
我在函数中引用了picName,它的值变成了downloadURL。

如果我的部分名称是“welcome”,那么我希望将 downloadURL 保存为数据库中的 welcomeimgUrl。对于“about”,它将是 aboutimgUrl 等。

这是我的方法:

editImage() {
      this.performingRequest = true
      let rest = this.restInfo
      let section = this.section
      let picName = this.section + 'imgUrl'
      console.log(picName)
      if (this.image) {
        this.image.generateBlob(
          blob => {
            let downloadURL
            let rand = (Math.random().toString(36).substring(2, 16) + Math.random().toString(36).substring(2, 16)).toUpperCase()
            let picRef = fb.storageRef.child('sectionPics/' + rand)
            picRef.put(blob).then((snap) => {
              picRef.getDownloadURL().then(function(downloadURL) {
                console.log('File available at', downloadURL)
                let dct2 = {}
                dct2[picName] = downloadUrl
                console.log(dct2)
                fb.restCollection.doc(rest.id).update({
                  dct2[picName]: downloadURL
                })
              })
            })
            setTimeout(() => {
              this.performingRequest = false
              this.image.remove()
            }, 2000)
          }
        )
      } else {
        
      }
    }

如何根据正在编辑的部分的名称更改我的 downloadURL 的数据库位置?

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    问题是更新 Firestore 文档时的地图创建。当您使用文字对象表示法编写映射时,键将被视为字符串,而不管使用相同名称定义的变量如何。相反,您期望发生的是键 picName 变为 picName value 而不是字符串 picName。有关代码方面的解释和修复方法,请参见下面的示例。

    picName = "foo"
    downloadUrl = "bar"
    dct1 = { picName: downloadUrl } 
    console.log(dct1) // => { "picName": "bar" } (key as string)
    
    // Solution
    dct2 = {}
    dct2[picName] = downloadUrl
    console.log(dct2) // => { "foo": "bar" } (key as variable value)
    

    编辑:在调用 firestore update 时更改的代码在语法上不正确。创建哈希图后,应将其直接传递给更新方法。请看下面的代码:

    let dct2 = {}
    dct2[picName] = downloadUrl
    fb.restCollection.doc(rest.id).update(dct2)
    

    【讨论】:

    • 感谢您的帮助...我认为您在正确的轨道上,但它还没有完全工作。我正在将您的代码添加到问题中的方法中。 dct2[picName]:downloadURL 导致意外错误
    猜你喜欢
    • 2018-04-28
    • 2018-08-06
    • 2015-08-07
    • 2019-05-24
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2021-02-24
    • 2013-05-26
    相关资源
    最近更新 更多