[Vuejs]-React to change of value prop only if changed outside of component

-2👍

To achieve your desired behavior, you can make use of a flag to differentiate between user input and external changes. Here’s an updated version of your code with the necessary modifications:

    <template>
  <input type="text" v-model="model" />
</template>

<script>
export default {
  props: ['value'],
  data() {
    return {
      internalValue: this.value,
      isUserInput: false
    };
  },
  watch: {
    value(newValue) {
      if (!this.isUserInput) {
        this.internalValue = newValue;
        this.doSomething(newValue);
      }
      this.isUserInput = false; // Reset the flag
    }
  },
  computed: {
    model: {
      get() {
        return this.internalValue;
      },
      set(value) {
        this.isUserInput = true;
        this.$emit('input', value);
      }
    }
  },
  methods: {
    doSomething(value) {
      // Perform your desired action here
      console.log('Value changed:', value);
    }
  }
};
</script>

In this updated code, we introduced a new data property called isUserInput which serves as a flag to indicate whether the value change originated from user input or from an external source.

The watcher now checks if isUserInput is false before executing doSomething() and updates the internalValue accordingly. This way, when the value changes externally, the watcher will be triggered and execute doSomething().

When the user modifies the input, the set function in the computed property is called, setting isUserInput to true and emitting an ‘input’ event to update the parent’s value.

Remember to use this component as follows:

<template>
  <div>
    <my-component v-model="myValue" />
  </div>
</template>

<script>
import MyComponent from '@/components/MyComponent.vue';

export default {
  components: {
    MyComponent
  },
  data() {
    return {
      myValue: ''
    };
  }
};
</script>

By using v-model, the parent component can bind the myValue property to the value prop of the MyComponent component. Any changes made to myValue outside of the component will trigger the watcher and execute doSomething().

On the other hand, user input will update the component’s internal value and emit the ‘input’ event to keep the parent in sync, but it won’t trigger the watcher or execute doSomething().

Leave a comment