Vue3中setup里怎么监听props变化?

打工人春萍 阅读 26

我刚从Vue2转到Vue3,现在在setup函数里用props传值,但发现props变了组件没反应。之前在Vue2里用watch可以直接监听,现在在setup里试了watch(props.xxx, ...)却报错说不能直接监听解构出来的值,这到底该怎么写才对?

我试过把整个props传给watch,但又不知道具体哪个属性变了,感觉很麻烦。有没有简洁又正确的写法?

import { watch } from 'vue'

export default {
  props: ['userId'],
  setup(props) {
    // 这样写会报错:Cannot destructure property 'userId' of 'props' as it is not reactive
    const { userId } = props
    watch(userId, (newVal) => {
      console.log('userId changed:', newVal)
    })
  }
}
我来解答 赞 10 收藏
二维码
手机扫码查看
暂无解答

暂无解答