Watch Vue Props with Computed Properties

In Vue, props are data passed from a parent component to a child component, and the child component cannot directly watch props. However, you can monitor props by using computed properties in the child component.

For example, in the scenario where a parent component passes a prop called myProp to a child component, we can use a computed property in the child component to monitor changes in myProp.

export default {
  props: ['myProp'],
  computed: {
    myPropWatcher() {
      return this.myProp;
    }
  },
  watch: {
    myPropWatcher(newVal, oldVal) {
      // 处理myProp的变化
    }
  }
}

By mapping myProp to a computed property called myPropWatcher, we can monitor changes to myProp and have the watcher automatically trigger when myProp changes.

Additionally, if you want to watch multiple props in a child component, you can use an object to watch them.

watch: {
  'myProp1': function(newVal, oldVal) {
    // 处理myProp1的变化
  },
  'myProp2': function(newVal, oldVal) {
    // 处理myProp2的变化
  }
}

This can achieve monitoring of multiple props. Hope this helps you.

bannerAds