admin管理员组文章数量:1203975
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:
Vueponent('my-images', {
props: ['images'],
template: `
<section>
<div v-for="(image, index) in images">
{{index}} - <img :src="image"/>
</div>
</section>
`
});
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>
`
});
Share
Improve this question
edited Mar 24, 2017 at 12:24
Jonatas Walker
14.2k6 gold badges56 silver badges82 bronze badges
asked Mar 24, 2017 at 12:16
Tadas MajerisTadas Majeris
3712 gold badges4 silver badges12 bronze badges
2
|
3 Answers
Reset to default 18<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>
You're good to go with this:
Vue.component('my-images', {
props: ['images'],
computed: {
imagesComputed: function () {
// just an example of processing `images` props
return this.images.filter((each, index) => index > 0);
}
},
template: `
<section>
<div v-for="(image, index) in imagesComputed">
{{index}} - <img :src="image"/>
</div>
</section>
`
});
And example for typescript
@Prop()
options: any[];
@Watch('options', {immediate: true})
optionsChanged(newVal: any[]) {
console.log('options changed ', newVal);
}
本文标签: javascriptHow to watch prop change in Vuejs componentStack Overflow
版权声明:本文标题:javascript - How to watch prop change in Vue.js component? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738593895a2101675.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
watch
a prop just like if it were a data item. – Roy J Commented Mar 24, 2017 at 12:22