Vue.js 2: Sorting ul list based on user input text

Is there a way to filter a list dynamically based on either the name or initials that a user types into an input field? I am currently utilizing vue.js 2 for this task. The list is populated by accessing a store variable which stores data from a JSON file.

STORE VARIABLE

$store.coin.coin

JSON example

{
 "coin": [
 {
  "initials": "DLR",
  "price": "0.727282",
  "volume": "1212",
  "change": "+1.22",
  "name": "dollar"
 }, ...
 ]
}

HTML

          <li>
            <div class="input-group search-box">
              <input id="filter-coins" v-model="search" placeholder="Filter" class="input-group-field" type="text">
            </div>
          </li>
          <li class="tabs-title" v-for="item in filteredItems" :key="item.initials" >
            <a href="#coinList" aria-selected="true">
              <div class="grid-x">
                <div class="auto cell">{{ item.initials }}</div>
                <div class="auto cell">{{ item.price }}</div>
                <div class="auto cell">{{ item.volume }}</div>
                <div class="auto cell">{{ item.change }}</div>
                <div class="auto cell">{{ item.name }}</div>
              </div>
            </a>
          </li>

METHOD

  export default {
    name: 'coins',
    search: '',
   computed: {
    filteredItems() {
      return this.$store.coin.coin.filter(item =>
        (item.name.toLowerCase().indexOf(this.search.toLowerCase()) > -1));
    },
   },
  };

store.js

import Vue from 'vue';
import Vuex from 'vuex';
import coin from '../data/coins-btc.json';

Vue.use(Vuex);

export default {
 state: {
  coin,
  },
 getters: {
  coin: state => state.coin,
 },
};

Answer №1

Below is a sample filter that can be used with either the initials or the name.

computed:{
  filteredItems(){
    let items = this.$store.getters.item.items
    // return all items if no filter is applied
    if (!this.search) return items

    // define the filter function
    let searchValue = this.search.toLowerCase()
    let filter = item => item.initials.toLowerCase().includes(searchValue) ||
                         item.name.toLowerCase().includes(searchValue)

    return items.filter(filter)
  }
}

Here is how you can implement this filter in your code.

console.clear()

const store = new Vuex.Store({
  state: {
    item: {
      "items": [
        {
          "initials": "ABC",
          "price": "10.25",
          "quantity": "100",
          "category": "food"
        },
        {
          "initials": "XYZ",
          "price": "15.45",
          "quantity": "50",
          "category": "electronics"
        },
        {
          "initials": "LMN",
          "price": "5.75",
          "quantity": "200",
          "category": "clothing"
        }        
      ]
    }
  },
  getters:{
    item: state => state.item
  }
})

new Vue({
  el: "#app",
  store,
  data:{
    search: null
  },
  computed:{
    filteredItems(){
      let items = this.$store.getters.item.items
      // return all items if no filter is applied
      if (!this.search) return items
      
      // define the filter function
      let searchValue = this.search.toLowerCase()
      let filter = item => item.initials.toLowerCase().includes(searchValue) ||
                           item.name.toLowerCase().includes(searchValue)
      
      return items.filter(filter)
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0e1c0c393b2313312d">[email protected]</a>"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.4.0/vuex.js"></script>
<div id="app">
  <ul>
    <li>
      <div class="input-group search-box">
        <input id="filter-items" v-model="search" placeholder="Filter" class="input-group-field" type="text">
      </div>
    </li>
    <li class="tabs-title" v-for="item in filteredItems" :key="item.initials" >
      <a href="#itemList" aria-selected="true">
        <div class="grid-x">
          <div class="auto cell">{{ item.initials }}</div>
          <div class="auto cell">{{ item.price }}</div>
          <div class="auto cell">{{ item.quantity }}</div>
          <div class="auto cell">{{ item.category }}</div>
        </div>
      </a>
    </li>
  </ul>

</div>

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

Determine a value by incrementing a number in a loop

+---+---+---+ | 1 | 0 | 0 | +---+---+---+ | 2 | 1 | 0 | +---+---+---+ | 3 | 2 | 0 | +---+---+---+ | 4 | 0 | 1 | +---+---+---+ | 5 | 1 | 1 | +---+---+---+ | 6 | 2 | 1 | +---+---+---+ | 7 | 0 | 2 | +---+---+---+ | 8 | 1 | 2 | +---+---+---+ | 9 | 2 | 2 | +--- ...

Reduce code length for generating DOM fragment with jQuery

I'm currently working on generating a tree of elements that will be used as an input for JsTestDriver unit tests. I've got some code to create this tree which involves using Document Object Model methods in JavaScript. I'm wondering if there ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Utilizing React to customize JVectorMap markers

Having an issue with a marker appearing in my React project https://i.stack.imgur.com/hkqnZ.jpg The markers are displaying correctly, but there is a persistent initial marker at 0,0 that I can't remove. Removing the 'markers' property from ...

What is the best way to make a selected link stand out with a highlight?

I'm having an issue with the code below that is supposed to keep the selected link highlighted, but it only flashes the green color on click. Can someone help me figure out what's going wrong here? #sidebarContent a:active{ background-colo ...

Is the ajaxToolkit PopupControlExtender malfunctioning? Could it be due to being outdated?

I recently tried following a tutorial on using ASP.NET Ajax Popup Control to display GridView row details. However, I encountered a runtime error when attempting to perform a mouseover action. The error message reads: Sys.ArgumentUndefinedException: Va ...

Utilize Vue template to access and interact with file contents

How can I read a file from the system using vue.js? For example: import fs from "fs"; var fs = require("fs"); fs.readFile("path"); I am experiencing an error when trying to import fs. What could be the issue? ...

Tips on sending information from Express to my HBS template

var Ticket = require('./models/ticket.js'); module.exports = function (app) { app.get('/',function (req, res) { Ticket.find({},function (err, tickets) { if(err) { res.sen ...

Unable to retrieve module from directive template in Angular

I am currently working on creating a wrapper component for ngAudio. This wrapper will act as the player with controls and will interact with ngAudio's functions. However, I am facing some scope issues with it. I can inject ngAudio into the component&a ...

Using script tags incorrectly (JavaScript platform game)

Currently, I am working on the 'create a platform game' project as outlined in Eloquent JavaScript, and I have encountered an issue related to script tags. As per the instructions in the book, we are advised to showcase our level using: <lin ...

One particular item in the list does not conform to the same formatting as the others

Having a formatting issue with the indexLink when populating an unordered list with links. Can't seem to dedent it properly no matter what I try. Here's the javascript snippet: function addCrumb() { /* reads from localStorage and determines wh ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

Exploring the animation potential of HTML5 canvas and Javascript through utilizing putImageData with animated gifs

I am interested in modifying the image data of each frame in an animated gif while it is playing in a web browser, using HTML5 canvas and Javascript. For instance, I would like to convert every frame to grayscale dynamically as the gif plays. Is this achie ...

Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click? The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-h ...

Persisting Undefined Values Even After Proper Prop Passing

I'm currently working on fetching and passing coaching data as props to another component for rendering on the frontend. I need to pass these props to the CoachingCard Component in order to display the coaching values. However, I'm encountering ...

Display one of two divs after clicking a button depending on the input from a form field

My apologies for my limited knowledge in JavaScript and jQuery. I'm attempting to show one of two divs based on input from a form. Specifically, there's a button next to a form field that asks users to enter their zip code to check if they are wi ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...