0

I have a object variable in which i need to watch some of the keys

My object

user{
 name,
 address,
 city,
 dob
} 

So I need to watch address and city properties

so the way i am doing it as below

watch:{
   'user.address' : (new,old)=>{
             //do something    
          },
   'user.city' : (new,old)=>{
             //do something    
          },
}

Now what i want let say in future if i want to watch some more properties inside user object the one way is to add new watcher for that property as i did above, is there any other way that i can do it dynamically without writing watch everytime.

Thanks

1 Answer 1

1

This is done by using deep watcher option:

watch:{
  user: {
    handler(new,old) {...},
    deep: true
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Hi @Estus I tried it is watching for all the properties inside that object I just wanted to watch specific properties, can you help me how to achieve that, as I wanted to check if some property value is changing than do something or else not.
You can use imperative watcher like this.$watch(() => pick(this.user, ['address', '...']), (newVal, oldVal) => ...), or define a key dynamically for $watch . This could be XY problem, maybe you need computeds or to make a state easier to handle. I can't think of a good reason to do what you asked about.
Sorry i am new to Vuejs i am working on my first project so don`t know how, but i am trying to update one properties based on changes happening in some properties. my user object has multiple properties but i wanted to watch only some of them
As said above, this is possibly solved with computeds. In my experience, the overuse of watchers means that computeds aren't used enough.
can you please update your answer with more details, sorry i am new so asking Thank you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.