【问题标题】:How to watch prop change in Vue.js component?如何查看 Vue.js 组件中的道具变化?
【发布时间】:2017-08-17 09:06:12
【问题描述】:

我正在将一组图像文件路径传递给一个组件。 我想知道如果我传递不同的数组,在 Vue.js 组件中观察道具变化的最佳方式是什么?

我正在使用引导轮播,所以想在数组更改时将其重置为第一个图像。 为了简单起见,我将代码示例简化为:

Vue.component('my-images', {
  props: ['images'],

  template: `
    <section>
      <div v-for="(image, index) in images">
        {{index}} - <img :src="image"/>
      </div>
    </section>
  `
});

【问题讨论】:

  • 你可以watch一个道具,就像它是一个数据项一样。
  • 欢迎反馈!

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:
<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>

【讨论】:

  • 你能解释一下这段代码吗?即为什么/如何工作?
  • 天哪!这个答案刚刚保存了我的几十行代码。我一直在寻找 componentWillReceiveProps,但在寻找 Vue.js。我必须在 Vue watchers 中查看每个单独的属性。但现在我可以在一个函数中观看它们。 :) 非常感谢@binaryify
【解决方案2】:

你很好:

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

【讨论】:

    【解决方案3】:

    打字稿示例

      @Prop()
      options: any[];
    
      @Watch('options', {immediate: true})
      optionsChanged(newVal: any[]) {
        console.log('options changed ', newVal);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 2017-12-14
      • 2021-09-07
      • 2019-03-25
      • 2017-07-08
      • 2017-04-09
      • 2019-05-31
      • 2019-10-31
      • 2016-08-09
      相关资源
      最近更新 更多