Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch props change on vuejs

Tags:

vue.js

vuejs2

I want to use watch for a props on a child component, but it's not working.

Here is my code :

props: {
    searchStore: {
        type: Object
    }
},
watch: {
    searchStore(newValue) {
        alert('yolo')
        console.log(newValue)
    }

And it's unfortunately not working

I've looked on this post and tried everything and nothing work : VueJs 2.0 - how to listen for `props` changes

I checked my props with Vue Devtools and it's changing.

Thanks in advance to the community !

like image 654
foufrix Avatar asked Jul 11 '18 19:07

foufrix


People also ask

Can you watch a prop Vuejs?

To watch for prop changes with the Vue. js Composition API, we can call the watch function. watch( () => props.

How do I listen to component prop changes Vue?

To listen for props changes with Vue. js, we can add a watcher for the prop. to watch the value of the myProp prop by setting watch. myProp to an object with immediate set to true to watch the initial value of the myProp prop.

How do I watch props in composition API?

To watch props change with Vue Composition API and Vue 3, we can use the watch function. to call watch to watch the selected prop. We get the latest and previous value of it from the parameters in the 3rd argument.

Do props update Vue?

As long as you're updating a reactive property (props, computed props, and anything in data ), Vue knows to watch for when it changes. All we have to do is update count , and Vue detects this change. It then re-renders our app with the new value!


1 Answers

based on that code, it should work, so the issue may be somewhere else. Can you post more code?

if you want to run immediately, you can use immediate. This is the syntax:

  watch: {
    searchStore: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {

      }
    }
  },

The deep: true setting will deep-watch for a change within the object.

When you are updating parts of this object in the parent component, make sure you use Vue's $set function.

this.$set(this.searchStore, 'myKey', {price: 12.22});

further reading: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

like image 168
Daniel Avatar answered Sep 27 '22 19:09

Daniel