【问题标题】:How to modify an object after axios get request is resolvedaxios get请求解决后如何修改对象
【发布时间】:2020-03-01 08:53:18
【问题描述】:

我在发出 axios get 请求后在 Vue 中设置对象 containerInfo 的 res.data,如下所示:

methods: {
    searchContainers(containerSearch) {
      this.containerQuery = JSON.parse(containerSearch.container_query)[0];
      this.imageBranch = JSON.parse(containerSearch.container_query)[1];
      this.containerInfo["image_branch"] = this.imageBranch
      this.url = this.containerQuery.split('/');

      axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`)
        .then(res => this.containerInfo = res.data)
        .then(this.containerInfo = [...this.containerInfo, this.imageBranch]);

    }

我想在vue中接收/设置数据对象后将this.imageBranch添加到containerInfo对象中。

问题是 axios res 收到后(需要几秒钟)会删除添加的 this.imageBranch 键/值。我知道我应该在承诺解决后添加它,但我不知道怎么做。

有人可以帮忙吗!

【问题讨论】:

  • 您需要将函数传递给 .then ... 其他任何内容都将被忽略(看看您的第二个 .then 是如何没有被传递函数的)
  • 你能提供一个例子@Bravo吗?
  • 第一个 .then 有一个作为参数传递的函数,第二个没有

标签: javascript vue.js axios es6-promise


【解决方案1】:

不要使用两个.then,而是只使用一个并在箭头函数内执行所有代码,如下所示:

methods: {
    searchContainers(containerSearch) {
        this.containerQuery = JSON.parse(containerSearch.container_query)[0];
        this.imageBranch = JSON.parse(containerSearch.container_query)[1];
        this.containerInfo["image_branch"] = this.imageBranch
        this.url = this.containerQuery.split('/');

        axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`)
            .then(res => {
                this.containerInfo = res.data;
                this.containerInfo = [...this.containerInfo, this.imageBranch]
            });

    }

【讨论】:

  • 我已经尝试了你的建议,但仍然收到相同的结果:(
  • @swarr35 - 取决于您检查的位置this.containerInfo
  • 我已经尝试了上述所有建议。我的this.imageBranch 会在发送资源后不断被删除。
【解决方案2】:

我建议使用清晰明了的 await/async 语法。所以代码应该是这样的

async searchContainers() {
  const res = await axios.get(`http://localhost:8000/get?name=${this.url[0]}/${this.url[1]}/${this.url[2]}&ver=${this.url[3]}`);
  this.containerInfo = res.data;
  this.containerInfo = [...this.containerInfo, this.imageBranch];
}

【讨论】:

  • 为什么不只是this.containerInfo = [...this.res.data, this.imageBranch];
  • 即使使用 await/async 语法,我仍然得到相同的结果
【解决方案3】:

我想通了。需要在对象中设置一个键:this.containerInfo.image_branch = this.imageBranch

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2021-12-05
    • 2020-10-14
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多