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

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

更新

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

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

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

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


当前回答

你试过这个吗?

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

其他回答

对于双向绑定,你必须使用.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; }

我认为在大多数情况下,Vue会在道具变化时更新组件的DOM。

如果这是你的情况,那么你可以使用beforeUpdate()或updated()钩子(docs)来观察道具。

如果你只对新val感兴趣而不需要旧val,你可以这样做

new Vue({ el: '#app', data: { text: '' }, components: { 'child': { template: `<p>{{ myprop }}</p>`, props: ['myprop'], beforeUpdate() { console.log(this.myprop) }, updated() { console.log(this.myprop) } } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <child :myprop="text"></child> <input v-model="text" placeholder="Type here to view prop changes" style="width:20em"> </div>

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

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

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

你试过这个吗?

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