computed计算属性依赖的响应式属性为对象时,只要依赖的属性变化(值同地址不同:变化),即使前后值相同,监听computed计算属性也是在变化

computed计算属性依赖的响应式属性为对象A时:

响应式属性A改变,当值相同,但是地址不同,computed的地址就在改变,监听computed计算属性值则始终在变化。

猜测:computed计算属性Obj为对象时,每次Obj变化后,即使变化前和变化后值相同,地址也不会相同了。

此外:watch监听对象时,值同地址不同时,也会执行监听事件

demo如下

<template>
  <el-form ref="form" :model="form" label-width="80px">
    <el-form-item label="a">
      <el-input v-model="form.a"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">a++</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  name: 'couponForm',
  computed: {
    formData () {
      return {
        a: this.form.a
      }
    }
  },
  watch: {
    formData: {
      deep: true,
      handler (newVal, oldVal) {
        console.log('newVal', newVal) // {a:1}
        console.log('oldVal', oldVal) // {a:1}
        console.log('newVal===oldVal?', newVal === oldVal) // false
        console.log('newVal==oldVal?', JSON.stringify(newVal) === JSON.stringify(oldVal)) // true
      }
    }
  },
  data () {
    return {
      form: {
        a: 1
      }

    }
  },
  methods: {
    onSubmit () {
    // this.form.a 进行了操作,虽然执行完毕后,值未变,但是对于formData来说,地址不同了,所以监听事件执行了
this.form.a = this.form.a + 1 this.form.a = this.form.a - 1 } } } </script>
原文地址:https://www.cnblogs.com/sakura-sakura/p/11131631.html