首页 > 解决方案 > 如何根据路由参数动态改变vuejs方法?

问题描述

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

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

如果我的部分名称是“welcome”,那么我希望将 downloadURL 保存为数据库中的 welcomeimgUrl。对于“关于”,它将是 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.jsvue-router

解决方案


问题是更新 Firestore 文档时的地图创建。当您使用文字对象表示法编写映射时,键被视为字符串,而不管使用相同名称定义的变量。相反,您期望发生的是键picName成为picName 而不是字符串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)

推荐阅读