After struggling with this issue for over a week, I've hit a roadblock and need some assistance.
I'm currently working on implementing a search filter in Vue 2 with Vuetify, but something isn't quite right.
Here's a snippet of the search filter code:
<v-text-field v-model="search" label="Look for name..."></v-text-field>
I have a two-way binding variable called 'search' in the component data for the text-field v-model.
Additionally, I have an array of items:
items: [
{
default: true,
name: 'Text 1',
},
{
default: false,
name: 'Text 2',
},
{
default: false,
name: 'Text 3',
},
{
default: false,
name: 'Text 4',
},
],
I'm rendering the list in a div using v-for:
<div v-for="(item, index) in filteredItems">
<div style="display: flex">
<input
type="radio"
:checked="item.default"
@click="changeDefault(item, index)"
/>
<h1>{{ item.name }}</h1>
</div>
</div>
This is how the component appears: View the rendered list and search filter
Wondering how the filter works? Check out the code snippet below:
filteredItems() {
if (this.search) {
return this.items.filter((item) => {
return item.name.toLowerCase().match(this.search);
});
} else {
return this.items;
}
},
Everything seems to be functioning properly, but there's an issue when I search for an item (e.g., 'Text 2') and click the radio button. Upon clearing the filter, it seems like nothing has changed.
It only happens when using the search method; clicking an item in the initial list changes the radio button as expected. View 'Text 2' search View after clearing the search
It appears that the list isn't rendering the new items properly. I'm really stuck here and would appreciate any help!
<template>
<v-app>
<v-main>
<v-text-field v-model="search" label="Look for name..."></v-text-field>
<div v-for="(item, index) in filteredItems">
<div style="display: flex">
<input
type="radio"
:checked="item.default"
@click="changeDefault(item, index)"
/>
<h1>{{ item.name }}</h1>
</div>
</div>
</v-main>
</v-app>
</template>
<script>
export default {
name: 'App',
components: {},
data: () => ({
search: '',
items: [
{
default: true,
name: 'Text 1',
},
{
default: false,
name: 'Text 2',
},
{
default: false,
name: 'Text 3',
},
{
default: false,
name: 'Text 4',
},
],
}),
methods: {
changeDefault(item, index) {
console.log(item);
let indexOfDefaultTrue = this.items.findIndex((item) => item.default === true);
console.log(indexOfDefaultTrue);
this.items[indexOfDefaultTrue].default = false;
this.items[index].default = true;
console.log(this.items);
},
},
computed: {
filteredItems() {
if (this.search) {
return this.items.filter((item) => {
return item.name.toLowerCase().match(this.search);
});
} else {
return this.items;
}
},
},
};
</script>