[英]How to watch prop change in Vue.js component?
我正在将一组图像文件路径传递给一个组件。 我想知道如果我传递一个不同的数组,在 Vue.js 组件中观察 prop 变化的最佳方法是什么?
我正在使用 bootstrap carousel,所以想在数组更改时将其重置为第一个图像。 为了简单起见,我将代码示例简化为:
Vue.component('my-images', {
props: ['images'],
template: `
<section>
<div v-for="(image, index) in images">
{{index}} - <img :src="image"/>
</div>
</section>
`
});
<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>
你很高兴这样做:
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>
`
});
和打字稿的例子
@Prop()
options: any[];
@Watch('options', {immediate: true})
optionsChanged(newVal: any[]) {
console.log('options changed ', newVal);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.