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

Vue监听数组对象属性值变化
博客讲述从后台请求数据,将数组存于data的commentList变量用于页面渲染,需随时监听数组中对象属性值变化,还提到利用vue.$set()方法重置来实现监听。

问题描述:开始我是从后台请求到的数据,将数组保存到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()重置 
        }
    });
},

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值