我正在尝试弄清如何使用VueJS中的for循环将数据分为两个级别
作为示例,我有一个VueJS应用,其中包含以下数据:
cars: [{
"make": "Ford",
"model": "Mustang"
}, {
"make": "Ford",
"model": "Thunderbird"
}, {
"make": "Ford",
"model": "Fairlane"
}, {
"make": "Chevrolet",
"model": "Camaro"
}, {
"make": "Chevrolet",
"model": "Chevelle"
}, {
"make": "Plymouth",
"model": "Barracuda"
}]
使用for循环在汽车之间循环很简单:
<div v-for="car in cars">
<div>Make: {{ car.make }}</div>
<div>Model: {{ car.model }}</div>
</div>
但是,如果我想按制造商对模型进行分组怎么办?我需要的输出是:
Ford
Mustang
Thunderbird
Fairlane
Chevrolet
Camaro
Chevelle
Plymouth
Barracuda
在VueJS中执行此操作的最佳方法是什么?
答案 0 :(得分:4)
您可以在计算属性中使用hideSplashAfter6: boolean = true;
this.zone = new NgZone({});
this.afAuth.auth.onAuthStateChanged((user) => {
this.zone.run(() => {
if (user) {
this.rootPage = HomePage;
this.splashScreen.hide();
this.hideSplashAfter6 = false;
} else {
this.rootPage = LoginPage;
this.splashScreen.hide();
this.hideSplashAfter6 = false;
console.log("Not logged in")
}
});
});
setTimeout(() => {
if(this.hideSplashAfter6) {
this.splashScreen.hide();
}
}, 6000)
:
npm outdated
模板可以像这样循环分组:
reduce
答案 1 :(得分:2)
@DigitalDrifter有很好的解决方案,但您可能会发现以下内容更易于阅读。但是效率较低,因此我绝对不会将其用于大型收藏(例如数千辆汽车)。
computed: {
makes() {
const makes = new Set();
this.cars.forEach(car => makes.add(car.make);
return Array.from(makes);
}
},
methods: {
models(make) {
return this.cars
.filter(car => car.make === make)
.map(car => car.model);
}
}
和模板中
<div v-for="(make, index) in makes" :key="index">
<p>Make: {{ make }}</p>
<ul>
<li v-for="(model, innerIndex) in models(make)" :key="innerIndex">
{{ model }}
</li>
</ul>
</div>
答案 2 :(得分:1)
为什么要在计算上浪费那么多的cpu而不是做一些具有ui友好结构的数据按摩?
props: {
cars: Array
},
data() {
return {
makes: _.groupBy(this.cars, 'make'); // _.groupBy is a lodash function
};
},
methods: {
// some CRUD methods
add() {},
update() {},
delete() {},
reconstruct() {
var result = [];
Object.keys(this.makes).forEach(key => {
result.push(...this.makes[key]);
});
return result;
}
}
<div v-for="(make, key) in makes" :key="key">
<p>Make: {{ make }}</p>
<ul>
<li v-for="(car, index) in make" :key="index">
{{ car.model }}
</li>
</ul>
</div>
您只需要在与API对话时进行构造/解构即可。
答案 3 :(得分:0)
您可以按照以下方式利用computed
属性,(运行此代码段以查看):
var app = new Vue({
el: "#app",
data: {
cars : [{
"make": "Ford",
"model": "Mustang"
}, {
"make": "Ford",
"model": "Thunderbird"
}, {
"make": "Ford",
"model": "Fairlane"
}, {
"make": "Chevrolet",
"model": "Camaro"
}, {
"make": "Chevrolet",
"model": "Chevelle"
}, {
"make": "Plymouth",
"model": "Barracuda"
}]
},
computed: {
groupedMakes() {
var makes={};
this.cars.forEach((item)=>{
if(makes[item.make]==undefined){
makes[item.make]=[];
makes[item.make].push(item.model)
}
else{
makes[item.make].push(item.model);
}
});
return makes;
}
}
})
<div id="app">
<div v-for="(make,index) in groupedMakes">
<h3>{{index}}</h3>
<ul>
<li v-for="model in make">
{{model}}
</li>
</ul>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>