【问题标题】:Alternative to Running Axios in Computed在 Computed 中运行 Axios 的替代方案
【发布时间】:2021-03-20 05:13:29
【问题描述】:

我正在从事一个涉及化学数据的高中项目。我需要从此 URL 获得响应并在另一个函数中引用它。当我尝试在挂载的函数中使用 descriptionURL 时,我收到一条错误消息,指出它未定义。任何不涉及第三方添加的帮助将不胜感激。

注意:properties.CID 来自挂载函数的请求。

computed: {
    description() {
      var descriptionURL = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + this.properties.CID + "/description/json"
      //eslint-disable-next-line no-console
      console.log(descriptionURL);
      axios
        .get(this.descriptionURL)
        //eslint-disable-next-line no-console
        .then(response => {this.descriptionText = response.data})
          //eslint-disable-next-line no-console
        .catch(function (error) {
          //eslint-disable-next-line no-console
          console.log(error);

        })
        return descriptionURL
    }
  },
}

【问题讨论】:

  • 能否提供一个demothis.properties.CID

标签: javascript vue.js axios


【解决方案1】:

我发现你的 sn-p 中有几件事令人费解。

首先,在 description() 计算属性的范围内定义了一个名为 descriptionURL 的变量。但是,axios 正在向 this.descriptionURL 发送请求,这将是在组件级别定义的变量,因此不是前面提到的 descriptionURL 变量。这是故意的吗?

此外,您的计算属性返回 descriptionURL,这可能不是您想要使用的内容。

此外,Computed properties should not have side effects,您似乎正在这样做(更改属性 descriptionText )。我建议使用方法而不是计算属性。

如果你真的希望你的计算属性返回 descriptionURL,那么你可以通过调用 this.description 来访问这个值(而不是 this.descriptionURL) 在 mounted().

最后,由于 API 调用需要一些时间来获得响应,因此不太可能在 mount() 中使用其结果。

如果您正在寻找替代方案,根据我目前对情况的理解,我将如何实现此功能:

data(){
  return{
    descriptionText: null,
  }
},
method: {
  get_description() {
    var descriptionURL = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + this.properties.CID + "/description/json"
    axios.get(descriptionURL)
    .then(response => { this.descriptionText = response.data })
    .catch((error) => { console.error(error) })
  },
  other_method_using_description(){

    // Check if descriptionText actually contains a description
    if(!this.descriptionText) {
      console.error('descriptionText is still null')
      return
    }

    // use this.descriptionText
  }
}

在此示例中,get_description 是一种用于使用来自 HTTP 请求的响应填充 descriptionText 属性的方法。

然后你可以在其他函数中使用这个属性,假设它已经接收到数据。

【讨论】:

    【解决方案2】:

    请尝试.get(descriptionURL) 而不是.get(this.descriptionURL),因为descriptionURLdescription() 范围内,而不是在vue 实例上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2019-04-04
      相关资源
      最近更新 更多