vue项目中遇到的一些问题记录

174 阅读1分钟

记录一些在项目中遇到的问题,持续更新...

1. 匿名对象作为props传值问题

这个问题在项目中前后出现两次了,每次都搞的头大,记录一下。

场景

  • 匿名对象作为props传给子组件
<template>
    <HelloWorld :msg="{ text: 'Object with no handle' }" :count="count"/>
    <button @click="count++">add</button>
</template>

<script setup>
import { ref } from "vue";
import HelloWorld from "@/components/HelloWorld.vue";

const count = ref(0);
</script>
  • 子组件HelloWorld接收并监听了这个props
<template>
    <p>{{ msg.text }}</p>
    <p>count: {{ count }}</p>
</template>

<script setup>
import { watch, toRef } from "vue";

const props = defineProps({
    msg: Object,
    count: Number
});

watch(toRef(props, 'msg'), (newVal, oldVal) => {
    console.log('"msg" has changed!');
    console.log(newVal, oldVal);
});
</script>
  • 代码效果

image.png

问题复现

点击按钮,count的值发生改变,此时即使msg的没有做任何更改,也会触发watch事件

image.png

尝试了多种情况,只有当子组件的其他props参数发生改变,才会出现这种情况。其他情况都不会触发,包括子组件自身的其他数据发生变化。

思考

  • 匿名对象没有句柄,在props发生更改,触发组件更新props值的过程中,找不到前一个绑定值的地址,所有会重新生成一个新的对象。前后两个对象虽然值都一样,但已经不是同一个,所以触发了watch事件。

todo

  • 其他props参数的值发生改变,匿名props又没发生改变,为什么会重新赋值,从而触发watch事件?