为什么嵌套对象在 Vue3 中不是响应式的?

问题描述 投票:0回答:1

我在 Vue 3 中更新响应式变量时遇到了问题。

为了处理 vue 3 中的逻辑,我定义了以下可组合项:

export const useAddCustomPackage = () => {
  // Reactive variables
  const selectedService: {
    title: string;
    description: string;
    period: number;
    data: {
      service: number;
      request_number: number;
      min_interval_time?: unknown;
      service_province?: unknown;
    }[];
  } = reactive({ title: "", description: "", period: 30, data: [] });

  const activeService: {
    [key: string]: IActiveServices;
  } = reactive({
    "ssl-checker": { active: false, requestNumber: 0, id: "", unitPrice: 0 },
    "up-time": { active: false, requestNumber: 0, id: "", unitPrice: 0 },
    traceroute: { active: false, requestNumber: 0, id: "", unitPrice: 0 },
    "interval(up-time)": {
      active: false,
      requestNumber: 0,
      id: "",
      unitPrice: 0,
      minIntervalTime: 0,
      servers: [],
    },
  });

  // Get services and add id to active services list
  const addIdsOfServices = async () => {
    try {
      const response = await fetchListOfServices();

      const listOfServices = response.data;

      for (const service of listOfServices) {
        activeService[service.title].id = service.id;
        activeService[service.title].unitPrice = service.unit_price;
      }
     
      console.log("list of active services", activeService);
    } catch (e) {
      throw new Error("error during fetching list of services");
    }
  };

 return {activeService,addIdsOfServices}
}

我在以下组件中使用了 addIdsOfservices :

 <script setup lang='ts'>
   import CustomPlanForm from "./CustomPlanForm.vue";
   import { useAddCustomPackage } from "../composables/useAddCustomService";
   // Composables
   const {
  selectedService,
  addSubservices,
  addServers,
  addChosenInterval,
  activeService,
  addIdsOfServices,
} = useAddCustomPackage();

onMounted(async()=>{await addIdsOfServices()})
 </script>

<template>
 
   <VCol
      md="12"
      class="d-flex justify-space-between align-center"
      v-for="service in Object.keys(activeService)"
      :key="service"
    >
      <CustomPlanForm
        :unit-price="activeService[service].unitPrice"
        :service-name="service"
        v-model:request-number="activeService[service].requestNumber"
        :cities="cities"
        @emit-servers="addServers"
        @emit-interval="addChosenInterval"
      />
    </VCol>

</template>

当通过 addIdsOfServices 函数添加新的 id 时,activeService[service] 将不会更新,也不会反应! 如何处理这个问题?

typescript vuejs3 nuxtjs3 vue-reactivity
1个回答
1
投票

您正在对反应性对象进行解构分配。

解构可以破坏反应性。

这是您可以在线搜索的常见主题,解决方案通常涉及使用

toRefs
来保持反应性。

https://vuejs.org/api/reactivity-utilities.html#torefs

© www.soinside.com 2019 - 2024. All rights reserved.