Watch props vue 3

Explanation of Watch Props in Vue 3

In Vue 3, the method of watching props has been slightly modified compared to Vue 2. The watch feature allows you to monitor changes in prop values and perform certain actions accordingly. Here is an example to help you understand:

    
      <template>
        <div>
          <h3>{{ propValue }}</h3>
        </div>
      </template>

      <script>
      export default {
        props: {
          propValue: {
            type: String,
            default: 'Initial value' // defining the default value
          }
        },
        watch: {
          propValue(newValue, oldValue) {
            console.log('New value:', newValue);
            console.log('Old value:', oldValue);
          }
        },
      }
      </script>
    
  

In the above example, we have a component with a prop named “propValue”. When the value of this prop changes, the watch method defined in the component will be triggered. It will log the new and old values of the prop to the console.

It is important to note that in Vue 3, the watch method is declared as a function within the component’s options object, instead of being placed directly within the component’s lifecycle hooks like in Vue 2. By doing this, Vue 3 ensures better encapsulation and composition.

Related Post

Leave a comment