在VueJs 2.0文档中,我找不到任何可以监听道具变化的钩子。

VueJs有这样的钩子像onpropsupdate()或类似的吗?

更新

正如@wostex建议的那样,我试着观察我的财产,但没有任何变化。然后我意识到我遇到了一个特殊的情况:

<template>
    <child :my-prop="myProp"></child>
</template>

<script>
   export default {
      props: ['myProp']
   }
</script>

我将父组件接收到的myProp传递给子组件。然后手表:{myProp:…不起作用。


当前回答

对我来说,这是一个礼貌的解决方案,让一个特定的道具发生变化,并用它创建逻辑

我将使用道具和变量计算属性来创建接收更改后的逻辑

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
  objectDetail: { // <--- we could access to this value with this.objectDetail
    type: Object,
    required: true
  }
},
computed: {
  _objectDetail: {
    let value = false
    // ...
    // if || do || while -- whatever logic
    // insert validation logic with this.objectDetail (prop value)
    value = true
    // ...
    return value 
  }
}

因此,我们可以在html渲染中使用_objectDetail

<span>
  {{ _objectDetail }}
</span>

或以某种方式:

literallySomeMethod: function() {
   if (this._objectDetail) {
   ....
   }
}

其他回答

如果myProp是一个对象,通常不可以更改。所以,手表永远不会被触发。为什么myProp不被改变的原因是你在大多数情况下只设置myProp的一些键。myProp本身仍然是一个。 试着看myProp的道具,比如“myProp”。A "应该有用。

在我的情况下,我需要一个解决方案,任何时候任何道具都会改变,我需要再次解析我的数据。我厌倦了为我所有的道具制作分离的观察者,所以我用了这个:

  watch: {
    $props: {
      handler() {
        this.parseData();
      },
      deep: true,
      immediate: true,
    },
  },

从这个例子中得到的关键点是使用deep: true,这样它不仅监视$props,而且还监视它的嵌套值,例如props. myprop

你可以在这里了解更多关于这款扩展手表的选择:https://v2.vuejs.org/v2/api/#vm-watch

@JoeSchr有答案。如果你不想要深度,还有另一种方法:true

 mounted() {
    this.yourMethod();
    // re-render any time a prop changes
    Object.keys(this.$options.props).forEach(key => {
      this.$watch(key, this.yourMethod);
    });
  },

你试过这个吗?

watch: {
  myProp: {
    // the callback will be called immediately after the start of the observation
    immediate: true, 
    handler (val, oldVal) {
      // do your stuff
    }
  }
}

https://v2.vuejs.org/v2/api/#watch

如果有人使用Vue 2的合成API,我下面的答案是适用的。 所以设置函数是

setup: (props: any) => {
  watch(() => (props.myProp), (updatedProps: any) => {
    // you will get the latest props into updatedProp
  })
}

但是,您需要从组合API导入手表函数。