quiet201 2021-12-17 11:28 采纳率: 100%
浏览 482
已结题

Vue3 setup中 watch不到对象的数据变化,不知道什么原因

问题遇到的现象和发生背景

Vue3 setup中 watch不到对象的数据变化

问题相关代码,请勿粘贴截图
**father.vue**

setup() {
 let testMsgObj = reactive({
    person1: {
     name: 'person1',
     age: 41,
    },

    person2: {
     name: 'person2',
     age: 42,
    },
 })
 
 let testMsg = testMsgObj.person1

 const handleSetLineChartData = () => {
    testMsg = testMsgObj.person2
    console.log(testMsg)
 }

    return {
      testMsg,
    }
}



**child.vue**

props: {
 testMsg: Object
},
setup(props) {
 let { testMsg } = props
 watch( () => testMsg, (val) => {
   console.log('testMsg---', val)
  },{ deep: true })
} 
运行结果及报错内容

无法看到 testMsg数据的变化

img

我的解答思路和尝试过的方法
我想要达到的结果

希望watch 可以监听 testMsg 变成peson2的数据 现在只看到 父级的组件 testMsg 改变了 watch并没打印出来 说明没监视到数据变化

  • 写回答

5条回答 默认 最新

  • 上官熊猫 2021-12-17 16:16
    关注

    需要注意两点:

    • 1.watch监听是响应式数据,原数据testMsg就不是响应式的,给testMsg加上ref就可以了;
    • 2.在获取props时不要使用解构。
    //父组件
    let testMsg = ref(testMsgObj.person1);
    const handleSetLineChartData = () => {
         testMsg.value = testMsgObj.person2;
       };
    
    //子组件
    watch(() => props.testMsg,(val) => {
            console.log("-----", val);
          },
          { deep: true }
        )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
  • 关注

    watch一般用来监听路由参数的变化。

    评论
  • 禅思院 前端领域优质创作者 2021-12-17 12:03
    关注

    let { testMsg } = toRefs(props)

    评论
  • 前端阿彬 前端领域新星创作者 2021-12-17 12:21
    关注

    reacrive的数据,你解构从里面拿数据,拿出来的不是响应式的。
    得torefs()转一下

    评论
  • quiet201 2021-12-20 17:29
    关注

    发现问题了
    1 testMsg 必须是 ref 模式
    2 watch 只能 props.testMsg (不要使用解构)
    多谢 超小少 指点 之前绕进去了

    let testMsg = ref(testMsgObj.person1)
    const handleSetLineChartData = (type) => { 
     testMsg.value = testMsgObj.person2
    }
    
    watch(
     () => props.testMsg, (val) => {
       console.log('watch--', val)
    })
    
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 12月28日
  • 已采纳回答 12月20日
  • 创建了问题 12月17日

悬赏问题

  • ¥30 android百度地图SDK海量点显示标题
  • ¥15 windows导入environment.yml运行conda env create -f environment_win.yml命令报错
  • ¥15 这段代码可以正常运行,打包后无法执行,在执行for内容之前一直不断弹窗,请修改调整
  • ¥15 C语言判断有向图是否存在环路
  • ¥15 请问4.11到4.18以及4.27和4.29公式的具体推导过程是怎样的呢
  • ¥20 将resnet50中的卷积替换微ODConv动态卷积
  • ¥15 通过文本框输入商品信息点击按钮将商品信息列举出来点击加入购物车商品信息添加到表单中
  • ¥100 这是什么压缩算法?如何解压?
  • ¥20 upload上传实验报错500,如何解决?(操作系统-windows)
  • ¥15 谁知道 ShaderGraph 那个节点可以接入 Particle System -> Custom Data