解决axios获取请求后如何修改对象

我在发出axios获取请求后,在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键/值。我知道在诺言解决后我应该添加它,但我不知道如何做。

有人可以帮忙吗!

zzzyq 回答:解决axios获取请求后如何修改对象

而不是使用两个.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]
            });

    }
,

我建议使用清晰明了的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.image_branch = this.imageBranch

本文链接:https://www.f2er.com/3162671.html

大家都在问