I have an array of objects in my Vue instance which consist of data from a MongoDB server, and an array of numbers which represents weeks. The Arrays looks like this:
courses: [
{Course: "A" Week: "1"},
{Course: "B" Week: "1"},
{Course: "A" Week: "2"},
{Course: "B" Week: "2"}
],
weeksInSemester: [1,2,3]
I display my data with ejs like this:
<div v-for="value in courses">
{{ value.Course }}
</div>
So far so good. Now I want to be able to filter the results from an tag like this:
<select>
<option v-for="weeks in weeksInSemester">
{{ weeks }}
</option>
</select>
I have been working/looking around for some time now, and not been able to find any solutions. What would be the best way to do this?
Use v-model
on the select:
<select v-model="selected">
Create a computed to filter the courses by the selected value:
computed: {
filteredCourses() {
if (this.selected) {
return this.courses.filter(v => v.Week === this.selected);
}
return this.courses;
}
}
Use the computed
with the v-for
:
<div v-for="value in filteredCourses">
{{ value.Course }}
</div>
Demo:
/***** APP *****/ new Vue({ el: "#app", data() { return { selected: null, courses: [ {Course: "A", Week: "1"}, {Course: "B", Week: "1"}, {Course: "A", Week: "2"}, {Course: "B", Week: "2"} ], weeksInSemester: [1,2,3] } }, computed: { filteredCourses() { if (this.selected) { return this.courses.filter(v => v.Week === this.selected); } return this.courses; } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-for="value in filteredCourses"> {{ value.Course }} </div> <select v-model="selected"> <option value="">All</option> <option v-for="weeks in weeksInSemester"> {{ weeks }} </option> </select> </div>
Edit for your question in comments:
To add an "All" option, you can insert a static option whose value
is the empty string, which won't pass the selected
check:
<select v-model="selected">
<option value="">All</option>
<option v-for="weeks in weeksInSemester">
{{ weeks }}
</option>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.