代码之家  ›  专栏  ›  技术社区  ›  Jaeger

如何用VueJS替换对象数组中的一个对象?

  •  0
  • Jaeger  · 技术社区  · 6 年前

    我正在用VueJS和AdonisJS建立一个网站,我正在设置一个只需设置 draft true false

    这个属性版本可以从索引中看到,在索引中可以看到所有的文章。我制作了一个表,其中有一个操作按钮可以切换属性,该按钮可以向Adonis发送一个带有ID的httppost请求。

    handlePublish (id) {
      this.$axios.post('/post/publish', {id: id}, {
        headers: {
          'Authorization': `Bearer [some token]`
        }})
        .then(response => {
          console.log(response)
          let toDelete = ''
          this.posts.map((post, index) => {
            if (post.id === id) {
              toDelete = index
            }
          })
    
        this.posts.splice(toDelete, 1)
        this.posts.push(response.data)
     })
     .catch(e => console.log(e.response))
    }
    

    但不知怎的,除了数据库之外,什么都得不到更新。

    先谢谢你

    1 回复  |  直到 6 年前
        1
  •  1
  •   Anurag Awasthi    6 年前

    您正在使用 map 地图 要通过返回新元素代替旧元素来更新数组,

    .then(response => {
        this.posts = this.posts.map((post, index) => {
            if (post.id === id) {
              return response.data
            }
        })
    }