我正在使用graphql从内容丰富的CMS中获取一堆数据。这些数据中的一个是一系列图像热点,其形式为:
product: {
hotspotOne: 'Lorem Ipsum'},
hotspotOneLeft: 5,
hotspotOneTop: 50,
hotspotTwo: 'dolor sit amet',
hotspotTwoLeft: 10,
hotspotTwoTop: 50,
...
}
但是,我想在vuejs / javascript中构建这些热点的数组并对其进行迭代,因为它们都具有相同的基本结构和交互性。
这是我目前分别显示每个热点的方式:
<slide v-for="hotspots in products.hotspots" :key="hotspots.id">
<div class="collection__product_container">
<div
class="collection__product_hotspot_container one"
v-if="hotspotOne"
>
<div class="collection__product_hotspot" :style="{top: hotspotOneTop + 'px',left: hotspotOneLeft + 'px}">{{hotspotOne}}</div>
</div>
<div
class="collection__product_hotspot_container one"
v-if="hotspotTwo"
...
>
...
</div>
...
</div>
</slide>
我如何构造每个热点的数组,如:
const hotspotArray = [{ hotspotOne, hotspotOneLeft,hotspotOneTop},{...},{...}]
...对于product.hotspots
中的每个产品,这样我就可以在该数组上执行v-for
来呈现上面的<slide/>
标记?
产品本身的graphql的结构是:
products {
id,
productTitle,
productPrice,
hotspots {
id
image {
file {
url
}
title
description
}
hotspotOne
hotspotOneTop
hotspotOneLeft
hotspotTwo
hotspotTwoTop
hotspotTwoLeft
...
}
}
当您从api收到响应时,您可以像这样转换响应,并使用转换后的产品而不是原始响应:
const productsFromApi = products => {
const convertedProducts = [];
// Object.keys Compatible with modern browsers.
Object.keys(products).forEach(key => {
if (isProductKey(key)) {
convertedProducts.push(buildProduct(products, key));
}
});
return convertedProducts;
};
const isProductKey = key => !key.endsWith("Last") && !key.endsWith("Top");
const buildProduct = (products, key) => ({
name: key,
left: products[`${key}Left`],
top: products[`${key}Top`],
});
有关与较旧环境的兼容性,请参见SO上的this answer。>>