Utilize the v-model directive for dynamic searching within a v-for rendered array in Vue.js

I haven't used Vue.js in a while. I am currently working on a simple app where I'm rendering items using a v-for from an array. I want to implement an input box with a v-model to search through the list of items (presets).

Code

<div class="row top20">
    <div class="col-md-3" v-for="preset in presets">
        <div class="template-block" :id="preset.id">
            <img src="http://placehold.it/120x120" v-bind:alt="preset.img" class="img img-responsive img-template">
            <h3>{{ preset.presetName }}</h3>
        </div>
    </div>
</div>

Data

searchQuery: '',
presets: [
    {id: '2', presetName: 'WooCommerce', img: 'woocommerce.png'},
    {id: '3', presetName: 'Magento', img: 'magento.png'},
    {id: '1', presetName: 'Custom', img: 'custom.png'}
]

I've tried using something like

<div class="col-md-3" v-for="preset in presets | searchQuery">
, but it doesn't seem to work. I thought about using a computed property, but I'm not sure how they work. Can someone provide a quick and easy solution?

Edit

I realized that I can use a method for searching. However, the issue is that it only displays exact matches. I would like the search function to display items that partially match the input.

Method

methods: {
    filterItems: function(presets) {
        var app = this;
        return presets.filter(function(preset) {
            return preset.presetName == app.searchQuery;
        })
    }
}

Edited view

<div class="col-md-3" v-for="preset in filterItems(presets)" :key="preset.presetName">

Answer №1

To achieve this, simply utilize the match method:

filterItems: function(presets) {
  var app = this;
  return presets.filter(function(preset) {
    let regex = new RegExp('(' + app.searchQuery + ')', 'i');
    return preset.presetName.match(regex);
  })
}

You can view the code in action on JSFiddle here: https://jsfiddle.net/u2vsbkap/

Answer №2

When working with a filter input, you can do the following:

<input type="text" v-model="searchQuery" />

To enhance the functionality of the function, make the necessary modifications as shown below:

filterItems: function(presets) {
var searchQuery = this.searchQuery;
var reg;

if (searchQuery === '') {
    return presets;
}
return presets.filter(function(preset) {
  return preset.presetName.indexOf(searchQuery) >= 0;
})

}

Answer №3

After doing some research, I came across this amazing repository on GitHub https://github.com/freearhey/vue2-filters.

<script src="https://cdn.jsdelivr.net/npm/vue2-filters/dist/vue2-filters.min.js"></script>

Alternatively,

You can install vue2-filters using npm:

npm install vue2-filters
import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

Sample Code:

<div class="col-md-3" v-for="preset in filterBy(presets, searchQuery)">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I specify the return type of a function in Typescript that can return more than one type?

I am facing a situation where I have a method called getFilters that retrieves various types of values. getFilters(): IListFilteringType {...} type IListFilteringTypeMultiSelect = (string | number)[]; type IListFilteringType = boolean | string | number | ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Code snippet that will emphasize the active page if there are multiple pages, such as highlighting page 2

My current project involves implementing a script to highlight the current page on a Tumblr blog. I found the script I am using here: $(function(){ $('a').each(function() { if ($(this).prop('href') == window.location.href) { ...

Unable to store the hashed password using bcrypt

I've been working on persisting hashed passwords using sequelize, bcrypt, and express. While the hash is being generated, it seems like the database entry occurs before the hash value is ready. My understanding of NodeJS is still in its early stages. ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

What is the best way to set one property to be the same as another in Angular?

In my project, I have defined a class called MyClass which I later utilize in an Angular component. export class MyClass { prop: string; constructor(val){ this.prop = val; } public getLength(str: string): number { return str.length; } ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

A guide on customizing column names in MUI Datatables through object keys

I'm currently facing an issue where I need to set the name of a column in MUI Datatables using an object key. Specifically, I want to set one of the column names with the first element of children.childName so that it displays a list of child names, b ...

Encountering an error message stating "TypeError: Unable to access properties of undefined (reading 'map')" while attempting to retrieve data

Having a React frontend, I am encountering an issue when trying to fetch data from my Node.js backend. Despite having the API structured correctly, I am facing difficulties. const SingleProductPage = () => { const { productId } = useParams(); cons ...

Turning off form validation in AngularJS for a short period of time

Successfully implemented client side form validation using AngularJS, but now I want to test my server side validation by sending incorrect data. However, AngularJS is preventing me from doing so! Is there a way around this without disabling Javascript an ...

Ensuring uniqueness of group by values in JavaScript when a textbox loses focus

Make sure the first column is unique by preventing duplicate entries in the second column textbox using JavaScript on blur event. <table rules="all" class="table table-bordered"> <tbody> <tr> < ...

How to apply CSS styling to a specific element using jQuery

When using $(".className"), all elements with the class .className are returned. How can I target a specific element by its index number to apply styling only to that element? <html> <head> <script src="https://ajax.googleapis.com/ajax ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

Flaw in Basic Function Logic Using HTML, JavaScript, and CSS

Need some help with the function onBall3Click1 (code is at the bottom). The ball should act like a lightbulb: ON - turn YELLOW, OFF - turn GRAY. I've been trying to figure out the logic behind it for so long and can't seem to find the issue... ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...

Is there a way to integrate a snap carousel in a vertical orientation?

I am looking to make a List utilizing the snap carousel component, but I'm having trouble getting it set up. Can anyone help me with this? ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

The lifespan of an Angular controller and its management of events

What is the best way to manage events, such as $rootScope or socket events, in an Angular controller without causing issues with event duplication? I have noticed that my controllers are not being destroyed properly, leading to problems when it comes to li ...

Is there a way to convert 'anObject' to a JSON string without including colons, backslashes, curly braces, or quotes?

This is a basic sentence. I only desire this and nothing <form><b>but</b></form> However, after performing some client-side manipulation with HTML... var newContent = JSON.stringify(req.body); and then updating MongoDb, var upda ...