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>
`
});
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.
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!
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.
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 .
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With