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

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

更新

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

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

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

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


当前回答

我认为在大多数情况下,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>

其他回答

@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: {
    $props: {
      handler() {
        this.parseData();
      },
      deep: true,
      immediate: true,
    },
  },

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

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

默认情况下,组件中的道具是反应性的,您可以在组件中的道具上设置监视,这将帮助您根据需要修改功能。下面是一个简单的代码片段来展示它是如何工作的

setup(props) {
 watch(
  () => props.propName,
  (oldValue, newValue) => {
    //Here you can add you functionality 
    // as described in the name you will get old and new value of watched property
  },
  { deep: true },
  { immediate: true } //if you need to run callback as soon as prop changes
)
}

希望这能帮助你得到你想要的结果。 祝你有愉快的一天。

对一些用例的有趣观察。

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

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

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

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

我的情况

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)
    }
  },