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

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

更新

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

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

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

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


当前回答

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

我的情况

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

其他回答

我使用计算属性,如:

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

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

props: [ 'resources' ]

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

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

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

你试过这个吗?

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

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

如果你添加道具,道具将会改变

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

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