v-for更新监测

v-for更新监测

当v-for遍历的目标结构改变, Vue触发v-for的更新

这些方法会触发数组改变, v-for会监测到并更新页面

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

这些方法不会触发v-for更新

  • slice()
  • filter()
  • concat()

注意: vue不能监测到数组里基础类型值的变化而更新, 如果需要请使用Vue.set(), 或者覆盖整个数组

<template>
  <div>
    <ul>
      <li v-for="item in arr">{{ item }}</li>
    </ul>
    <button @click="soBtn">排序</button>
    <button @click="reBtn">翻转</button>
    <button @click="jBtn">截取前3</button>
    <button @click="upBtn">点击改掉第一个元素的值</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [3, 15, 10, 1, 19, 32],
    };
  },
  methods: {
    soBtn() {
      this.arr.sort();
    },
    reBtn() {
      this.arr.reverse();
    },
    jBtn() {
      this.arr = this.arr.slice(0, 3);
    },
    upBtn() {
      // this.arr[0] = "老李"; // 页面无变化 - vue无法监测数组里值的改变
      // 可以使用数组提供的方法
      // 数据目标, 索引, 新值
      // Vue.set(this.arr, 0, "老李"); // 静态方法set
      this.$set(this.arr, 0, "老李"); // 实例方法$set
    },
  },
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值