【问题标题】:Can not delete post's comment reactively in Vue.js无法在 Vue.js 中反应性地删除帖子的评论
【发布时间】:2019-06-14 19:10:25
【问题描述】:

在我的类似博客的 Vue.js 应用程序中,帖子在 v-for 循环中呈现。当每个帖子下的按钮被点击时,它的 cmets 将从服务器获取并像这样进行属性,因为 post 对象没有 comments 属性:

  `this.$set(post, 'comments', res.data.comments) ;`

渲染 cmets 的代码是这样的:

<div v-for="(c, j) in post.comments" :key="j">                           
    <span>{{c.body}}</span> 
    <span v-if="post.user_id==userId" @click="delComment(c, post)">Delete me!</span>
</div>

以及删除方法:

  delComment(c, post) {
    const payload = {
           token: this.token,
           cid: c.id
      }
    axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
    .then( (res)=> {       
      post.comments = this.post.comments.filter((comment)=>{
         return comment.id != c.id
      });      
      this.$set(post, 'comments', post.comments) ;
    })
    .catch( error => {  
      console.log(error);
    });
  }, 

但是当我单击删除链接时,我在控制台中收到此错误:

TypeError: Cannot read property 'comments' of undefined
    at eval (Home.vue?76f2:540)

我该如何解决这个问题?

【问题讨论】:

    标签: javascript vue.js vuejs2 axios vue-component


    【解决方案1】:

    您在post 之前缺少this

     //v-------------//here
      this.post.comments = this.post.comments.filter((comment)=>{
         return comment.id != c.id
      }); 
    

    这里:

          //----------v--------------------v
          this.$set(this.post, 'comments', this.post.comments) ;
    

    更新:

    我假设您的数据对象中有一个名为 post 的属性,如下所示:

      data(){
         return{
            post:[]
           ...
            }
       }
    

    所以在这种情况下,您应该删除post 变量之前的所有this

    【讨论】:

    • 这仍然给TypeError: Cannot read property 'comments' of undefined
    • 那么 `this.$set(post, 'cmets', post.cmets) ;` 你还应该在 post 之前添加这个吗?
    • 我仍然收到TypeError: Cannot read property 'comments' of undefined
    • 在您提供的代码中,我只能看到导致此问题的这些情况,请提供任何使用 comments 属性的代码 sn-p
    • 我认为你误解了this 在这里指的是什么。
    【解决方案2】:

    好吧,我意识到罪魁祸首是this.post.comments.filter((comment) 中的一个额外的this

    工作代码是这样的:

    delComment(c, post) {
        const payload = {
               token: this.token,
               cid: c.id
          }
        axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
        .then( (res)=> {       
          post.comments = post.comments.filter((comment)=>{
             return comment.id != c.id
          });      
          this.$set(post, 'comments', post.comments) ;
        })
        .catch( error => {  
          console.log(error);
        });
      }, 
    

    感谢大家分享您的想法!

    【讨论】:

    • 我假设post 是数据对象属性,抱歉
    • 对不起,如果我不够清楚。感谢您的努力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多