如何查看 Vue.js 组件中的 prop 变化?
How to watch prop change in Vue.js component?
我正在将一组图像文件路径传递给组件。
我想知道如果我传递一个不同的数组,在 Vue.js 组件中观察道具变化的最佳方式是什么?
我正在使用 bootstrap 旋转木马,所以想在数组更改时将其重置为第一张图片。
为了简单起见,我将代码示例简化为:
Vue.component('my-images', {
props: ['images'],
template: `
<section>
<div v-for="(image, index) in images">
{{index}} - <img :src="image"/>
</div>
</section>
`
});
你可以接受这个:
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>
`
});
<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>
打字稿示例
@Prop()
options: any[];
@Watch('options', {immediate: true})
optionsChanged(newVal: any[]) {
console.log('options changed ', newVal);
}
我正在将一组图像文件路径传递给组件。 我想知道如果我传递一个不同的数组,在 Vue.js 组件中观察道具变化的最佳方式是什么?
我正在使用 bootstrap 旋转木马,所以想在数组更改时将其重置为第一张图片。 为了简单起见,我将代码示例简化为:
Vue.component('my-images', {
props: ['images'],
template: `
<section>
<div v-for="(image, index) in images">
{{index}} - <img :src="image"/>
</div>
</section>
`
});
你可以接受这个:
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>
`
});
<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>
打字稿示例
@Prop()
options: any[];
@Watch('options', {immediate: true})
optionsChanged(newVal: any[]) {
console.log('options changed ', newVal);
}