typescript,vue3组合式。我定义了goods的响应式数据:id,title,imageUrl,gallery,description,price,stock。现在我通…
- User
typescript,vue3组合式。我定义了goods的响应式数据:id,title,imageUrl,gallery,description,price,stock。现在我通过api取得一个商品的数据,我要将它更新到goods,但如果数据中的字段不在goods中、或字段的值为null,则不应该更新到goods中。写出代码
- 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 函数来管理这些逻辑。 - User
上面的需求怎样才能做到不用@ts-ignore
- 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这一条件。