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

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

更新

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

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

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

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


当前回答

@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方法本身是否被调用通过安慰内部的东西。一旦确定要调用手表,就用您的业务逻辑将其粉碎。

watch: { 
  myProp: function() {
   console.log('Prop changed')
  }
}

如果你的道具myProp有嵌套项,这些嵌套项不会是反应性的,所以你需要使用像lodash deepClone这样的东西:

<child :myProp.sync="_.deepClone(myProp)"></child>

就这样,不需要监视或其他任何东西。

对一些用例的有趣观察。

如果您通过道具从存储中监视数据项,并且在同一存储中多次更改数据项,则不会监视该数据项。

但是,如果您将数据项更改分离为相同突变的多个调用,它将被监视。

This code will NOT trigger the watcher: // Somewhere in the code: this.$store.commit('changeWatchedDataItem'); // In the 'changeWatchedDataItem' mutation: state.dataItem = false; state.dataItem = true; This code WILL trigger the watcher at each mutation: // Somewhere in the code: this.$store.commit('changeWatchedDataItem', true); this.$store.commit('changeWatchedDataItem', false); // In the 'changeWatchedDataItem' mutation: changeWatchedDataItem(state, newValue) { state.dataItem = newValue; }

不确定你是否已经解决了这个问题(如果我理解正确的话),但这是我的想法:

如果父节点接收myProp,并且你希望它传递给子节点并在子节点中观看它,那么父节点必须有myProp的副本(不是引用)。

试试这个:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'parent': {
      props: ['myProp'],
      computed: {
        myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
      }
    },
    'child': {
      props: ['myProp'],
      watch: {
        myProp(val, oldval) { now val will differ from oldval }
      }
    }
  }
}

在html中:

<child :my-prop="myInnerProp"></child>

实际上,在这种情况下处理复杂的集合时,你必须非常小心(传递几次)

我使用道具和变量计算属性,如果我需要创建逻辑后接收更改

export default {
name: 'getObjectDetail',
filters: {},
components: {},
props: {
    objectDetail: {
      type: Object,
      required: true
    }
},
computed: {
    _objectDetail: {
        let value = false
        ...

        if (someValidation)
        ...
    }
}