Enhance your VuetifyJS list in VueJS 2 by integrating search and sort features

I want to implement a basic search and sort feature for a list in VuetifyJS. Check out this CodePen example of the list: https://codepen.io/anon/pen/bxGGgv

What is the recommended approach to achieve this in VueJS 2?

HTML:

<v-list two-line>
  <template v-for="(item, index) in items">
      <v-list-tile
        :key="item.title"
        avatar
        ripple
        @click="toggle(index)"
      >
        <v-list-tile-content>
           <v-list-tile-title>{{ item.title }}</v-list-tile-title>
           <v-list-tile-sub-title class="text--primary">
               {{ item.headline }}
           </v-list-tile-sub-title>
           <v-list-tile-sub-title>{{ item.subtitle }}</v-list-tile-sub-title>
        </v-list-tile-content>
      </v-list-tile>
      <v-divider
        v-if="index + 1 < items.length"
        :key="index"
      ></v-divider>
  </template>
</v-list>

JS:

  export default {
    data () {
      return {
        selected: [2],
        items: [
          {
            action: '15 min',
            headline: 'Brunch this weekend?',
            title: 'Ali Connors',
            subtitle: "I'll be in your neighborhood doing errands this weekend. Do you want to hang out?"
          },
          {
            action: '18hr',
            headline: 'Recipe to try',
            title: 'Britta Holt',
            subtitle: 'We should eat this: Grate, Squash, Corn, and tomatillo Tacos.'
          }
        ]
      }
    },
  }

Answer №1

If you want to organize and filter your data in Vue, consider defining a computed property within your class. This computed property can handle both filtering and sorting functionalities.

For an example implementation, check out this CodePen

new Vue({
    el: '#app',
    data: {
        selected: [2],
        search: '',
        items: [{
                action: '15 min',
                headline: 'Brunch this weekend?',
                title: 'Ali Connors',
                subtitle: "I'll be in your neighborhood doing errands this weekend. Do you want to hang out?"
            },
            {
                action: '2 hr',
                headline: 'Summer BBQ',
                title: 'me, Scrott, Jennifer',
                subtitle: "Wish I could come, but I'm out of town this weekend."
            },
            {
                action: '6 hr',
                headline: 'Oui oui',
                title: 'Sandra Adams',
                subtitle: 'Do you have Paris recommendations? Have you ever been?'
            },
            {
                action: '12 hr',
                headline: 'Birthday gift',
                title: 'Trevor Hansen',
                subtitle: 'Have any ideas about what we should get Heidi for her birthday?'
            },
            {
                action: '18hr',
                headline: 'Recipe to try',
                title: 'Britta Holt',
                subtitle: 'We should eat this: Grate, Squash, Corn, and tomatillo Tacos.'
            }
        ]
    },
    computed: {
        filteredItems() {
            return _.orderBy(this.items.filter(item => {
                return item.title.toLowerCase().includes(this.search.toLowerCase()) ||
                    item.action.toLowerCase().includes(this.search.toLowerCase()) ||
                    item.headline.toLowerCase().includes(this.search.toLowerCase()) ||
                    item.subtitle.toLowerCase().includes(this.search.toLowerCase());
            }), 'headline');
        }
    },
    methods: {
        toggle(index) {
            const i = this.selected.indexOf(index)

            if (i > -1) {
                this.selected.splice(i, 1)
            } else {
                this.selected.push(index)
            }
        }
    }
})

Answer №2

Here's an alternative approach that may not adhere to the standard method, but could be worth trying...

To filter the input in the search, start by adding a v-model search and an array searchItem. Make sure to initialize searchItem in the mounted hook. Then create a computed property called filteredItems. I've utilized the .filter() function along with .match() for added flexibility, especially if you plan on using regex which will return an array.

Alternatively, you can also consider using .includes(), depending on your preference.

HTML (changes)

<v-toolbar>
   <v-text-field
     v-model="search" //include this
     ...
   ></v-text-field>
</v-toolbar>

<v-list two-line>
  <template v-for="(item, index) in filteredItems"> //modify items to filteredItems
   ...
  </template>
</v-list>

JS:

data () {
  return {
    search: '',
    selected: [2],
    searchItem: [],
    items: [
       // place your items here
    ]
  }
},

mounted() {
  setTimeout(() => this.searchItem = this.items)
},

computed: {
 filteredItems() {
    return this.searchItem.filter((item) =>{
         return item.title.toLowerCase().match(this.search)  || 
                item.headline.toLowerCase().match(this.search) || 
                item.subtitle.toLowerCase().match(this.search) || 
                item.action.toLowerCase().match(this.search)
    })
  }
}

Demo:

You can check out your updated Codepen here

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

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

Getting parameters from a URL with a React frontend and Express backend: A step-by-step guide

I am currently developing a react application with an express backend. I am in the process of integrating socket io chat functionality into the frontend. Everything is functioning properly, but I am now looking to extract parameters from the URL in order t ...

Utilize an enum from a shared library by exporting it and incorporating it into a TypeScript project

Currently, I am in the process of developing a library where a React component is being exported along with some interfaces and an enum. After compiling the typescript project, I realized that the library is specifically for React and not typescript, so I ...

Adding an array to a JSON array

I am trying to insert additional data into a JSON structure. Here is the current structure: [ { "name": "Sam", "ride": "My Ride test", "session": "6htbgumjtmnxko6r", "info": null }, ] The variables I have are as fo ...

Change the background image on your iPhone and Android device using the Appcelerator app

I'm looking for a way to change the wallpaper on both iPhone and Android devices from within my app. I've searched online, but couldn't find any solutions using Appcelerator's APIs. Can anyone help? ...

What is the best way to show a message of success once the user has been redirected to the homepage?

Currently, I have a registration form utilizing AJAX and PHP for validation. Error messages can be displayed on the registration page if the user does not correctly fill out the form. Upon successful registration, the user is redirected back to the home pa ...

Exploring viewport settings for a collection of meshes in Three.js

What is the most effective method for creating a viewport for a collection of meshes in three js? In my situation, I have a THREE.Group comprised of many THREE.Mesh instances. My objective is to establish a viewport specifically for this group, where ...

Using the HERE Maps JavaScript API to implement custom styles from a JSON file

TLDR: How can I change the map style using a .json file from HERE maps editor? After creating a "custom" style in the new HERE map style editor and exporting it as a single .json file, I encountered difficulties applying this styling due to lack of clear ...

Interactive navigation feature developed using VueJS

Attempting to implement a reactive navigation system that changes based on user authentication status. Following a login action in the application, a token is stored in local storage. If this token exists, I aim to display a logout button. Despite trying v ...

The parent's setState does not trigger the child's componentWillReceiveProps

Within my application, there is a parent component and a child component with props connected to the parent's state. When I call setState in the parent component, the componentWillReceiveProps function of the child component does not always get trigg ...

What is the method to determine the size of a Map object in Firestore database?

I currently have two elements within a document: an empty array, and a map object containing three components. If the array is empty, it transforms into type array. In this case, I can execute console.log(vehicles.Motorcycles.length) to receive a return of ...

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

Changing data in vue

I am utilizing a mixin in my Vue code to both add and override data properties. While I can successfully add new data, I am facing issues when trying to override existing data values. Below is a snippet of the code: var mixin = { data: function() { ...

Converting document.querySelector into a user-friendly format with React hooks

Is there a way to convert the process of fetching an element using querySelector and adding a reference to a div using document.querySelector into something that can be done with React hooks? import ReactDOM from "react-dom"; import h337 fro ...

Is it possible to restructure the address 51.xx.xx.xx:33xxx:user:pass to display as user:[email protected] :33xxx instead?

I am facing an issue with my current code where it only returns one proxy because it keeps rewriting over the existing ones. I want to avoid creating a new file and instead update the 'proxies.txt' file with each new proxy. const fs = require("f ...

Issue where CSS modal does not appear when clicked after being toggled

I've been working on a custom modal design that I want to expand to fill the entire width and height of the screen, similar to how a Bootstrap modal functions. The goal is to have a container act as a background with another inner div for content How ...

Emphasize text within the input field

Is there a way to create an input textarea that can detect words from an array in this.state and highlight those words as the user types text? Here is what I'm aiming for: The list of words: https://i.sstatic.net/eOx7G.png The input textarea examp ...

Adjusting element sizes in HTML5 Canvas

I am currently facing an issue with my canvas container, which has a width of 100% and a height of 50%. When I draw lines on it using x and y coordinates like this: context.moveTo(20, 20); context.lineTo(50, 20); context.stroke(); The problem arises when ...