简体   繁体   中英

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>
  `
});
<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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM