Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Watchers only once the component is entirely loaded

Hello,

Is it possible to set watchers so that they watch the changes only when the component is entirely loaded ?

That's useful for cascading select option fields.

When I ned to edit a model, while loading the existing datas, I don't want the values to be watched, but only when the user manually selects another option.

Thanks for your help.

Vincent

0 likes
2 replies
rodrigo.pedra's avatar
Level 56

Well you can register watchers on the fly, by using this.$watch(...) in Vue 2, or by importing the watch helper in Vue 3.

In the Vue 2 case, calling this.$watch(...) will return a deregistration callback that you should manually save and call when you unmount or destroy the component.

But I think it is easier to just ignore inputs from an "uninitialized" watcher, for example using the object notation which works for both Vue 2 and 3:

<template>
  <!-- ... -->
</template>

<script>
export default {

  data() {
    // where city depends on province, and province on country
    return {
      country: null,
      province: null,
      city: null,
    };
  },

  watch: {
    country(newValue) {
      if (!newValue) {
        this.state = null;
        this.city = null;
        
        return;
      }
      
      // load states from this country
    },

    state(newValue) {
      if (!newValue) {
        this.city = null;
        
        return;
      }
      
      // load cities from this country
    },

    city(newValue) {
      if (!newValue) {
        return;
      }
      
      // do something with city
    },
  },
  
};
</script>
1 like
vincent15000's avatar

@rodrigo.pedra This seems not to work in my case. But this let me think using the old value.

I have solved my problem like this.

watch: {
  'student.path_id' (pathId, oldValue) {
  	if (oldValue && pathId > 0) {
			axios.get(route('api.paths.projects.list', pathId)).then(response => {
			  this.projects = response.data
			  this.student.project_id = null
			})
  	}
  }
},
1 like

Please or to participate in this conversation.