Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

typescript,vue3组合式。我定义了goods的响应式数据:id,title,imageUrl,gallery,description,price,stock。现在我通…

  1. User

    typescript,vue3组合式。我定义了goods的响应式数据:id,title,imageUrl,gallery,description,price,stock。现在我通过api取得一个商品的数据,我要将它更新到goods,但如果数据中的字段不在goods中、或字段的值为null,则不应该更新到goods中。写出代码

  2. Assistant

    在 Vue 3 的 Composition API 中,我们可以使用 reactive 函数来定义响应式数据,以及 toRefs 帮助我们解构响应式对象。对于你的需求,更新 goods 数据时要确保只更新已定义的字段,且排除值为 null 的字段。以下是一个可能的实现方案:

    首先,定义你的响应式 goods 对象:

    import { reactive, toRefs } from 'vue';
    
    interface Goods {
      id?: string;
      title?: string;
      imageUrl?: string;
      gallery?: string[];
      description?: string;
      price?: number;
      stock?: number;
    }
    
    // 初始化响应式对象:
    const goods = reactive<Goods>({
      id: undefined,
      title: undefined,
      imageUrl: undefined,
      gallery: undefined,
      description: undefined,
      price: undefined,
      stock: undefined
    });
    

    然后定义一个更新 goods 的函数,它会根据特定的规则更新 goods 中已有的字段:

    function updateGoods(newData: Partial<Goods>) {
      for (const key in newData) {
        if (newData[key] !== null && key in goods) {
          // @ts-ignore
          goods[key] = newData[key];
        }
      }
    }
    

    在实际请求数据并更新到 goods 时,可以如下操作:

    import { ref } from 'vue';
    import axios from 'axios';
    
    // 假设你有一个API函数来获取商品数据
    async function fetchGoodsData(goodsId: string) {
      try {
        const response = await axios.get<Goods>(`/api/goods/${goodsId}`);
        const goodsData = response.data;
        
        // 更新goods响应式数据
        updateGoods(goodsData);
      } catch (error) {
        console.error('Failed to fetch goods data:', error);
      }
    }
    
    // 假设你在某个组件的setup函数中调用fetchGoodsData
    export default {
      setup() {
        const goodsId = ref('some-goods-id');
        
        // 取得商品数据并更新goods数据
        fetchGoodsData(goodsId.value);
        
        // 将goods对象的属性转为独立的reactive引用
        return {
          ...toRefs(goods)
        };
      }
    };
    

    请注意,fetchGoodsData 函数被用来从 API 获取数据,并使用 updateGoods 来更新响应式的 goods 对象。在此示例中,axios 被用于做 HTTP 请求。

    确保你的逻辑正确处理了任何潜在的异步执行问题(例如,处理竞态条件)。如果在组件的生命周期中多次使用到获取和更新goods数据的逻辑,你可能需要考虑把相关的逻辑封装在 Vue 组件的 onMounted 生命周期钩子中,或者抽象成一个自定义的 composable 函数来管理这些逻辑。

  3. User

    上面的需求怎样才能做到不用@ts-ignore

  4. Assistant

    要避免使用 @ts-ignore,你可以确保 TypeScript 知道你在处理的键是 Goods 类型中的有效键。这可以通过确保键属于 Goods 类型的键的联合类型来完成。我们可以使用 keyof 关键字来获得类型的键的联合类型,并用守卫语句来确保键是有效的。下面是如何实现的:

    import { reactive, toRefs } from 'vue';
    
    interface Goods {
      id?: string;
      title?: string;
      imageUrl?: string;
      gallery?: string[];
      description?: string;
      price?: number;
      stock?: number;
    }
    
    const goods = reactive<Goods>({
      id: undefined,
      title: undefined,
      imageUrl: undefined,
      gallery: undefined,
      description: undefined,
      price: undefined,
      stock: undefined
    });
    
    function updateGoods(newData: Partial<Goods>) {
      (Object.keys(newData) as Array<keyof Goods>).forEach((key) => {
        const newValue = newData[key];
        if (newValue !== null && newValue !== undefined) {
          goods[key] = newValue;
        }
      });
    }
    

    通过将 Object.keys(newData) 的返回类型强制转换为 Array<keyof Goods>,你告诉 TypeScript 这是 Goods 类型允许的键的列表。这样,当你访问 goods[key] 时,TypeScript 将知道 key 是 Goods 类型的有效属性键,因此不会产生类型错误。

    这种方法利用了 TypeScript 的类型断言功能来缩小键的类型,而不是使用 @ts-ignore 忽略类型错误。

    请注意,我也增加了对 undefined 的检查,因为如果 API 返回的是 undefined,那么你可能也不希望这个值覆盖 goods 中的原始值。如果你希望在 null 或 undefined 时都不更新值,那么上述检查是适当的。如果你只关心 null,你可以移除 newValue !== undefined 这一条件。