Vue监听数组和对象的变化

工作中常会遇到一些数据变化了,但是视图未更新的情况,自己写了一些demo简单测试了一下。
https://www.bilibili.com/video/BV1rV411B7TD

iShot2020-07-17下午02.08.22

<template>
  <div>
    <h1>yes 可以监听 no 不可以监听</h1>
    <div>nums:{
    
    {
    
    nums}}</div>
    <button type="button" @click="handleArr('add')">数组添加</button>
    <button type="button" @click="handleArr('edit')">数组修改</button>
    <button type="button" @click="handleArr('del')">数组删除</button>
    <button type="button" @click="handleArr()">直接赋值</button>
    <p>时间:{
    
    {
    
    person.time}}</p>
    <p>问题:{
    
    {
    
    person.question}}</p>
    <p>答案:{
    
    {
    
    person.anwer}}</p>

    <button @click="handleObj('add')">新增答案属性</button>
    <button @click="handleObj('edit')">修改时间属性</button>
    <button @click="handleObj('del')">删除答案属性</button>
    <button @click="handleObj()">直接赋值</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      nums: [1, 2, 3],
      person: {
    
    
        time: "00:00:00",
        question: "一起爬山么?"
      }
    };
  },
  created() {
    
    },
  methods: {
    
    
    /* yes 可以监听 no 不可以监听 */
    handleArr(type) {
    
    
      switch (type) {
    
    
        case "add":
          // this.nums.push(111, 222); //yes
          this.nums[3] = 444; //no
          break;
        case "edit":
          // this.nums.splice(1, 1, 88); //yes
          // this.$set(this.nums,1,88) //yes
          this.nums[1] = 88; //no
          break;
        case "del":
          // this.nums.shift(); //yes
          delete this.nums[0]; //no
          // this.nums.length=2 //no
          break;
        default:
          this.nums = [111, 222, 333]; //yes
          break;
      }
      console.log(this.nums);
    },
    handleObj(type) {
    
    
      switch (type) {
    
    
        case "add":
          this.person.anwer = "不了不了";
          break;
        case "edit":
          let nowDate = new Date();
          this.person.time = nowDate.toLocaleTimeString();
          // this.$set(this.person,'time',nowDate.toLocaleTimeString())
          break;
        case "del":
          delete this.person.anwer;
          break;
        default:
          this.person = {
    
    
            time: "a",
            question: "b",
            anwer: "c"
          };
          break;
      }
      console.log({
    
     ...this.person });
    }
  }
};
</script>

<style>
</style>

总结:

数组:

  • 可以监听到的情况
    如push、splice、=赋值(array=[1,2,3])
  • 无法监听到的情况
    使用下标索引修改数组元素的值(较常见) eg: arr[1]=88
    使用长度(length)修改数组长度 eg: arr.length=2
  • 解决方法
    1.this.$set(arr,index,val);
    2.splice(index,length,val);
    3.临时变量做中转,重新赋值数组

对象:

  • 可以监听的情况
    直接赋值 eg: obj = {name:‘yxf’}
    obj.name=‘zhangsan’
  • 无法监听的情况
    对象的增加和删除, delete
  • 解决方法
    1.this.$set(obj, key, val)
    2.使用Object.assign(), 直接赋值

猜你喜欢

转载自blog.csdn.net/qq_42816550/article/details/107407637