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

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

更新

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

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

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

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


当前回答

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

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

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

其他回答

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

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

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

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

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

我使用计算属性,如:

    items:{
        get(){
            return this.resources;
        },
        set(v){
            this.$emit("update:resources", v)
        }
    },

在这种情况下,Resources是一个属性:

props: [ 'resources' ]

你可以观察道具,在道具改变时执行一些代码:

new Vue({ el: '#app', data: { text: 'Hello' }, components: { 'child' : { template: `<p>{{ myprop }}</p>`, props: ['myprop'], watch: { myprop: function(newVal, oldVal) { // watch it console.log('Prop changed: ', newVal, ' | was: ', oldVal) } } } } }); <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <child :myprop="text"></child> <button @click="text = 'Another text'">Change text</button> </div>

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