Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch prop change in Vue.js component?

I'm passing an array of image filepaths to a component. I'm wondering what would be the best way to watch a prop change in Vue.js component, if I pass a different array?

I'm using bootstrap carousel, so wanna reset it to first image when array changes. In order for simplicity I reduced code example to this:

Vue.component('my-images', {
  props: ['images'],

  template: `
    <section>
      <div v-for="(image, index) in images">
        {{index}} - <img :src="image"/>
      </div>
    </section>
  `
});
like image 861
Tadas Majeris Avatar asked Mar 24 '17 12:03

Tadas Majeris


People also ask

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.

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!

Does component Rerender when props change Vue?

If the key stays the same, it won't change the component, but if the key changes, Vue knows that it should get rid of the old component and re-create a new one. Every time that forceRerender is called, our prop componentKey will change.

How do I pass a prop to a dynamic component?

To pass props dynamically to dynamic component in Vue. js, we can check the current component being rendered in component and pass in the props accordingly. to check the value of currentComponent in the currentProps` computed property. And we return an object with the props we want to pass into the child component .


1 Answers

<template>
  <div>
    {{count}}</div>
</template>

<script>
export default {
  name: 'test',
  props: ['count'],
  watch: {
    '$props':{
      handler: function (val, oldVal) { 
        console.log('watch', val)
      },
      deep: true
    }
  },
  mounted() {
    console.log(this.count)
  }
}
</script>
like image 138
Binaryify Avatar answered Nov 15 '22 19:11

Binaryify