1 回答

TA貢獻1831條經(jīng)驗 獲得超4個贊
一種解決方案是先對帖子進行排序,然后再按地址進行分組。
使用Array.prototype.sort()
和String.prototype.localeCompare()
,創(chuàng)建一個實用程序(名為sortPosts()
)以在計算的 prop 中使用,該實用程序?qū)?code>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)
? })
現(xiàn)在,我們將使用您已有的相同邏輯對這些帖子進行分組,但我們必須將局部resorts
變量的數(shù)據(jù)類型從更改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>
添加回答
舉報