1 回答
TA贡献1831条经验 获得超4个赞
一种解决方案是先对帖子进行排序,然后再按地址进行分组。
使用Array.prototype.sort()
和String.prototype.localeCompare()
,创建一个实用程序(名为sortPosts()
)以在计算的 prop 中使用,该实用程序将按country
, state
, city
, thenstreet_name
字段对帖子进行排序:
const sortPosts = posts =>
posts.slice().sort((a,b) => {
const countryA = a.acf.address.country
const countryB = b.acf.address.country
const stateA = a.acf.address.state
const stateB = b.acf.address.state
const cityA = a.acf.address.city || '' // can be undefined in Google Maps API
const cityB = b.acf.address.city || '' // can be undefined in Google Maps API
const streetA = a.acf.address.street_name
const streetB = b.acf.address.street_name
return countryA.localeCompare(countryB) || stateA.localeCompare(stateB) || cityA.localeCompare(cityB) || streetA.localeCompare(streetB)
})
现在,我们将使用您已有的相同逻辑对这些帖子进行分组,但我们必须将局部resorts
变量的数据类型从更改Object
为Map
,因为Object
迭代并不总是遵循插入顺序,这会破坏排序sortPosts()
:
export default {
computed: {
resorts() {
// BEFORE:
// const resorts = {};
const resorts = new Map();
if (this.$store.state.loading === false) {
sortPosts(this.$store.state.posts).forEach((post) => {
const c = post.acf.address.country;
const s = post.acf.address.state;
// BEFORE:
// resorts[c] = resorts[c] || {};
// resorts[c][s] = resorts[c][s] || [];
// resorts[c][s].push(post);
if (!resorts.has(c)) {
resorts.set(c, new Map());
}
const stateMap = resorts.get(c);
if (!stateMap.has(s)) {
stateMap.set(s, []);
}
stateMap.get(s).push(post);
});
}
return resorts
},
}
}
从 v2.6.12 开始,v-for
不支持Map
s,因此使用Array.from()
使其可迭代v-for
:
<section v-for="[country, countryData] in Array.from(resorts)" :key="country">
<h1 v-html="country" />
<section class="state" v-for="[state, posts] in Array.from(countryData)" :key="state" :class="state.toLowerCase()">
<h5 v-html="state" />
<ul>
<li v-for="(post, resort) in posts" :key="post.id">
...
</li>
</ul>
</section>
</section>
添加回答
举报