VUE watc method monitoring + JSON copy implementation to detect whether the object has been modified

Here we only describe how to solve the monitoring of objects. First, simulate a demand scenario, as shown in the figure:

In fact, in the case of a small amount of data, you only need to add an @input event for each input, but it will be very cumbersome in the case of a large amount of data.


I have also borrowed a lot of methods of deep copy and shallow copy, which is a little cumbersome to implement. If you want to judge which field value in the object has changed, you may need to use the combination of watch and computed to achieve it. Vue official also gives Answers about this and why


Having said so much, I want to talk about what I think is the easiest way, that is to convert the array into a string, I will paste the code directly

1. The value bound to the HTML button

<el-button :disabled="!isDisable" @click="preservation" type="primary">保存</el-button>

2. Data in data

data() {
      return {
        wxData:{},
        wxDataCopy:{},
        isDisableWx:false,
      };
    },

3. watch monitoring

//watch时将深拷贝的数据和newVal都push到数组中进行判断
watch:{
      wxData: {
        handler: function(newVal) {
          let arr1 = []
          let arr2 = []
          //遍历对象
          for (let key in newVal) {
            arr1.push(newVal[key])
          }
          for (let key in this.wxDataCopy) {
            arr2.push(this.wxDataCopy[key])
          }
          //按钮状态
          this.isDisableWx = JSON.stringify(arr1) == JSON.stringify(arr2) ? false : true
        },
        deep: true
      }
      
    },

//从后端获取第一次加载的数据
created() {
      getconfigKeys().then(res => {
        res.msg = JSON.parse(res.msg)   //这段忽略
        this.wxData = res.msg   //watch监听时的newVal(arr1)
        this.wxDataCopy = JSON.parse(JSON.stringify(this.wxData))  //对比newVal(arr2)
      })
    },

//最后保存完毕后别忘记置空wxData和wxDataCopy、重新调用一下请求接口,不然数据不会触发watch渲染按钮的状态哦~

Finally, I hope that everyone will criticize and give advice.

Guess you like

Origin blog.csdn.net/weixin_57246783/article/details/128780826