Vue 监听对象数组(包含多个对象的数组)

问题描述:开始我是从后台请求到的数据,将数组保存到data中的commentList数组变量中,利用数组中的对象值来进行页面渲染,需要随时监听到数组中对象属性值的变化。

数据形式:

data() {
   commentList: [
        {
          commentid: "01fc7e2c-cded-4567-8059-e6e71f583396",
          content: "计算机系统标引论文内容特征的词语",
          create_time: "2019-05-07",
          isOpenReply: false,
          isShowComment: false,
          replys: Array(0),
          userid: "8",
          username: "wtt"
        }
   ]
},

页面渲染:

 <div class="commentItem" v-for="(item,index) in commentList" :key="index">
       <span class="userSpan">{{item.username}}</span>
       <span class="commentTime">{{item.create_time}}</span>
       <div class="comment-list-box">
           <div class="comment-list">
               {{item.content}}
               <div class="reply">
                  <a @click="showComment(item,index)">查看回复</a>
               </div>
               <!--回复列表 -->
               <div class="replyListBox" v-if="item.isShowComment">
                  .......
               </div>
            </div>
        </div>
    </div>

 

监听:

watch: {
    commentList: {
      handler: function(newVal, oldVal) {
        // console.log("newVal:", newVal);
        // console.log("oldVal:", oldVal);
      },
      deep: true
    }
  },

 

  利用vue.$set()方法重置 ;   

showComment(item, index) {
    this.commentList.forEach(commentItem => {
        if (commentItem.commentid == item.commentid) {
          commentItem.isShowComment = !commentItem.isShowComment;
          this.$set(this.commentList, index, commentItem);   //将改变项利用$set()重置 
        }
    });
},

 


版权声明:本文为Tingting_Wang152原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。