Answer the question
In order to leave comments, you need to log in
How to add select filtering to an existing search?
Implemented search for characters by name, I want to add filtering (by character.species) to this search by select:
<select name="" id="">
<option value="" disabled selected>Select yout option</option>
<option value="">alive</option>
<option value="">dead</option>
<option value="">unknown</option>
<template>
<main>
<div class="search-form">
<input type="text" placeholder="Поиск..." v-model="search" />
<select name="" id="">
<option value="" disabled selected>Select yout option</option>
<option value="">alive</option>
<option value="">dead</option>
<option value="">unknown</option>
</select>
</div>
<div class="all-characters">
<div
class="character_card"
v-for="character in searchCharacter"
:key="character.id"
>
<div class="character_info">
<img class="character_image" :src="character.image" alt="" />
<div class="character_name">
<a href="">{{ character.name }}</a>
</div>
<div class="character_add-info">
<span>{{ character.gender }}</span>
<span>{{ character.status }}</span>
<span>{{ character.species }}</span>
</div>
</div>
</div>
</div>
<button v-if="page !== 34" @click="loadMore" class="load-more_button">
Ещё
</button>
</main>
</template>
<script>
import axios from "axios";
export default {
name: "CharList",
data() {
return {
search: "",
characters: [],
page: 1,
};
},
beforeMount() {
this.getTodos();
},
methods: {
getTodos() {
axios
.get("https://rickandmortyapi.com/api/character/")
.then((response) => (this.characters = response.data.results));
},
loadMore() {
this.page++;
axios
.get("https://rickandmortyapi.com/api/character/?page=" + this.page)
.then((response) => this.characters.push(...response.data.results));
console.log(this.characters);
},
},
computed: {
searchCharacter() {
return this.characters.filter((character) => {
return character.name.toLowerCase().includes(this.search.toLowerCase());
});
},
},
};
</script>
Answer the question
In order to leave comments, you need to log in
Add a property to the component that will contain the current value of the drop-down list:
data: () => ({
status: '',
...
computed: {
statuses() {
return [...new Set(this.characters.map(n => n.status))];
},
...
<select v-model="status">
<option value="">< ALL ></option>
<option v-for="n in statuses">{{ n }}</option>
</select>
computed: {
filteredCharacters() {
const search = this.search.toLowerCase();
const status = this.status;
return this.characters.filter(n => (
(!search || n.name.toLowerCase().includes(search)) &&
(!status || status === n.status)
));
},
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question