Vue:对象在父组件中发生了两次更改,但在子组件中仅触发了一次“深度监视”

时间:2019-04-12 03:35:11

标签: vue.js vuejs2

我在项目中嵌套了组件:我想通过数组对象activeGiftList在两个组件之间进行通信

父组件视图:

    <div
      id="giftContainer"
      class="giftList"
      @click="hideBoard"
    >
      <template
        v-for="(item, index) in activeGiftList"
      >
        <send-gift-message
          v-if="item"
          :key="item.giftId"
          :gift-item="item"
          :gift-index="index"
          @changeActiveGiftList="changeActiveGiftList"/>
      </template>
    </div>

父亲组件js:

 watch: {
   activeGiftList: {
      handler: function (n) {
        if (n) {
          console.log('father: watch obj', n)
        }
      },
      deep: true
    }
 }

儿童部分:

  props: {
    giftItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    giftIndex: {
      type: Number,
      default: 0
    }
  },
  data () {
    return { flag: false }
  },
  watch: {
    giftItem: {
      handler: function (val, oldVal) {
        if (val) {
          this.flag = true
          console.log('child: watch obj', val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    console.log(this.flag, 'step 1')
  },
  mounted () {
    console.log(this.flag, 'step 2')
    setTimeout(() => {
      console.log(this.flag, 'step 3')
    }, 500)
  },

我两次更改了this.activeGiftList
first:[] => [{...}] //通过发布请求进行更改

second:[{...}] => //使用数组的find方法拾取目标对象并在其上添加其他属性,然后使用$set覆盖原始对象通过相同的index

这是console.log的结果:

father: watch obj, [{...}]
child: watch obj, {...}
false, step 1
false, step 2
father: watch obj, [{...}] // add one property on it.
true, step 3

即使我在vue watcher中使用了deep,并使用this.$set(this.activeGiftList, 0, newObj)覆盖了数组中的原始对象以触发第二次更改,我还是很困惑,但仍然无法观看第二次更改子组件。并且无法从子组件DOM中的新属性获得更改。

我还尝试过更改同一对象的存在属性,子组件似乎与父组件发生了相同的变化,是否有什么好主意可以帮助我解决此问题?

0 个答案:

没有答案
相关问题