在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 "应该有用。

在我的情况下,我没有得到任何信息,也无法检索信息。一定要在手表内部使用试扣

我的情况

setup(props, { emit, attrs, slots, expose }) {
...
....
..... 
}
.....
  watch: {
    isModalActive: function () {
      console.log('action:: ', this.props.isModalActive) // here cause error undefined and no error information on my inspect element dunno why
    }
  },

所以当我试图安慰别人的时候

  watch: {
    isModalActive: function () {
      console.log('action:: ') // this work and printed
      console.log('action:: ', this.props.isModalActive)
    }
  },

手表功能应该放在子组件中。没有父母。

对于双向绑定,你必须使用.sync修饰符

<child :myprop.sync="text"></child>

更多细节…

你必须在子组件中使用watch属性来监听和更新任何更改

  props: ['myprop'],
  watch: { 
    myprop: function(newVal, oldVal) { // watch it
      console.log('Prop changed: ', newVal, ' | was: ', oldVal)
    }
  }

对一些用例的有趣观察。

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

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

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