小编mog*_*wan的帖子

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

当父组件的数据更新并通过 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,但它无法检测旧值或新值。它不记录任何输出

使用 …

vue-props vuejs3 vue-composition-api

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

vue-composition-api ×1

vue-props ×1

vuejs3 ×1