Vue 3 Composition API:当父组件更新值时动态更新子组件 props

Ale*_*lex 6 vue-props vuejs3 vue-composition-api

当父组件的数据更新并通过 prop 时,我试图更新 prop 值。当我向下传递父值时,父值始终会更新,但不会在子组件中更新或重新渲染。它会在第一次访问子组件时传递给 prop,但不会在父组件中更新数据时传递给 prop。

下面是父组件:

<script setup>
    import { inject, watchEffect, ref } from "vue";
    import ChildComponent from "@/components/ChildComponent.vue"
    const { state } = inject("store");
    const cart = ref(state.cart);

    watchEffect(() => (cart.value = state.cart));

</script>
<template>
      <ChildComponent
       v-for="(item, index) in cart?.items"
       :key="index"
       :cartItem="item"
      />
</template>
Run Code Online (Sandbox Code Playgroud)

下面是子组件(仅在第一次加载时记录,不再加载):

<script setup>
    import { ref, watchEffect } from "vue";
    
    const { cartItem } = defineProps({
      cartItem: !Object
    });

    const item = ref(cartItem);

    watchEffect(() => {
      console.log(item.value)
    });
        
</script>
Run Code Online (Sandbox Code Playgroud)

我尝试以多种方式使用 Watch,但它无法检测旧值或新值。它不记录任何输出

使用 watch 的子组件示例:

<script setup>
    import { ref, watch } from "vue";
    
    const { cartItem } = defineProps({
      cartItem: !Object
    });

    const item = ref(cartItem);

    watch(() => item.value, (oldValue, newValue) => {
      console.log(oldValue)
      console.log(newValue)
    });
            
</script>
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 2

我最终通过使用 v-if 重新渲染子组件来解决该解决方案。

<script setup>
    import { inject, watchEffect, ref } from "vue";
    import ChildComponent from "@/components/ChildComponent.vue"
    const { state } = inject("store");
    const cart = ref(state.cart);
    const render = ref(true);
    
    // Checks when the cart changes from the store
    watchEffect(() => {
      if(cart.value) {
        render.value = true
      }
      else {
        render.value = false
      }
    };
    
</script>
<template>
    <div v-if="render">
      <ChildComponent
       v-for="(item, index) in cart?.items"
       :key="index"
       :cartItem="item"
      />
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)