Implementing a feature to display recent searches in a Vuejs searchbar

enter() {
            this.selection = this.matches[this.current];
            this.open = false;
        },
  change() {
            if (this.open == false) {
                this.open = true;
                this.current = 0;
            }
            
            
            if(this.search == "") {
                this.isSearchText = false;
            } else {
                this.isSearchText = true;
            }
            
        },
     inputChanged(event) {
            if (event.code == "ArrowUp" || event.code == "ArrowDown")
              return;
      
            this.filteredUsers = [];
      
            if (event.code == "Enter")
              return;
      
            var filtered = this.users.filter((user) => {
              return user.text.match(this.search)
            });
      
            this.isOpen = true
            this.filteredUsers.push(...filtered)
      
      
            // console.log(this.filteredUsers)
          },
   
     onArrow(event) {
            if (this.filteredUsers.length > 0) {
              this.arrowCounter = event.code == "ArrowDown" ? ++this.arrowCounter : --this.arrowCounter;
              if (this.arrowCounter >= this.filteredUsers.length)
                this.arrowCounter = (this.arrowCounter) % this.filteredUsers.length;
              else if (this.arrowCounter < 0)
                this.arrowCounter = this.filteredUsers.length + this.arrowCounter;
              this.setResult(this.filteredUsers[this.arrowCounter].text);
            }
          },
<input class="form-control bg-light-blue" id="SearchText"  type="text" v-model="search"
        @keydown.enter = 'enter'
        @input = 'change'
        @keyup="inputChanged"
        @keydown.down="onArrow"
        @keydown.up="onArrow"
    />
For instance, imagine using the search function on Amazon to look for a book, then returning to the search bar and finding your previously searched items saved. I am seeking similar functionality in Vue.js.

I desire to replicate this feature within Vue.js

Answer №1

After browsing the Flipkart website, I took a closer look at their search input feature. It consists of an input tag paired with an unordered list. Intrigued by this design, I decided to create a sample component inspired by it.

UPDATE: I have now implemented functionality to display or hide search history, along with setting a maximum length for the history log.

Introducing InputWithList.vue

<template>
  <div class="input-with-list">
    <h4>Input with List</h4>
    <div class="row">
      <div class="col-md-6">
        <div class="input-group">
          <input type="text" class="form-control" v-model="searchValue" @keyup.enter="processSearch"
            @click="onClick" @input="onInput">
          <div class="input-group-append">
            <button class="btn btn-outline-secondary" type="button" @click="processSearch">Search</button>
          </div>
        </div>
        <div class="form-group">
          <ul class="list-group" v-if="showSearchHistory">
            <li class="list-group-item" v-for="(item, index) in searchHistory" :key="index"
              @click="selectPreviousSearch(index)">{{ item }}</li>
          </ul>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <button type="button" class="btn btn-secondary" @click="clearHistory">Clear history</button>
      </div>
    </div>
</div>
</template>

<script>
  export default {
    data() {
      return {
        searchValue: '',
        searchHistory: [],
        showSearchHistory: false,
        searchHistoryMaxLength: 5
      }
    },
    methods: {
      processSearch() {
        if ( this.searchHistory.indexOf(this.searchValue) === -1) {
          this.searchHistory.push(this.searchValue);
          if (this.searchHistory.length > this.searchHistoryMaxLength) {
            // Remove the first (oldest) element
            this.searchHistory.shift();
          }
        }
        this.searchValue = '';
      },
      selectPreviousSearch(index) {
        this.searchValue = this.searchHistory[index];
        this.showSearchHistory = false;
      },
      clearHistory() {
        this.searchHistory = [];
        this.searchValue = '';
      },
      onClick() {
        // Toggle show/hide
        this.showSearchHistory = !this.showSearchHistory;
      },
      onInput() {
        this.showSearchHistory = false;
      }
    }
  }
</script>

<style scoped>
  li:hover {
    background-color:gainsboro;
  }
</style>

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

Modifying the href attribute of links within various occurrences of an element using jQuery based on its content

Here is an illustration of a recurring element on a webpage <td class=" market all"> <a href="linktosomesite?param=123" target="_blank">123</a> </td> Similar elements change the parameter, resulting in links like: <td clas ...

How can I correctly parse nested JSON stored as a string within a property using JSON.parse()?

I am having trouble decoding the response from aws secretsmanager The data I received appears as follows: { "ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000", "Name": "token", "VersionId&qu ...

Eliminate the dropdown menu from an HTML table

I have a table with dropdown lists in each row's second column. How can I remove a dropdown list from a row if the value in that row is "Delivery"? Check out my fiddle here: https://jsfiddle.net/fp67wLqz/ window.onload = $('#my_id tbody tr&apo ...

Vuejs - Enhancing User Experience with Multiple Unique Loading Indicators for Various States

I am in search of a spinner like the one showcased in this tutorial on Adding Loading Indicators to Your Vue.js Application. However, I need this spinner to function differently for various elements and states. For instance, when the first image is being ...

Vue Select - Enhancing search capabilities by including meta-data in the search process

Looking to integrate the vue-select plugin into my vue app, here is the code I have: <v-select :options="options" label="country" :reduce="country => country.meta.code" v-on:input="set"/> The options avai ...

Ensure that jQuery waypoints become unstuck upon reaching the footer area

Currently, I have successfully implemented jQuery waypoints for a sticky social media navigation. The only issue is that when the footer element is reached, the sticky navigation continues to scroll. My ideal scenario would be for the sticky nav to remain ...

Tips for Achieving a Smooth Transition Effect with jQuery while Modifying an Image's Attribute

I am facing an issue with the code I have written to change the image source on mouse hover. While it does change the image src, the effect is quite jerky and abrupt. Is there a way to slow down the animation effect? <script> $(document).re ...

Retrieve information from a mysql database and incorporate it into a javascript program

I am attempting to extract data from a MySQL database and utilize it in JavaScript. I stumbled upon this resource which was quite helpful, however, I am facing difficulties in displaying the information (as I have limited experience with jQuery). I suspect ...

What is the best way to eliminate HTML tags from strings embedded in state data?

Firstly, I utilize the 'axios' library to fetch data from an API. Next, I store the received data in my State variable. Finally, I display the information stored in the state within a table format. The issue that I am facing is that the Strings ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

Encountering a problem during the installation of the udev module in a Node.js

When I run the command below: npm install udev I encounter the following error message: npm WARN enoent ENOENT: no such file or directory, open '/home/mitesh/package.json' npm WARN mitesh No description npm WARN mitesh No repository field. ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

Having trouble executing `npm start` command

After running npx create-react-app and then npm start, I encountered an error message https://i.sstatic.net/Uj5EC.png. Despite following the suggested solutions, the error persists. Any idea why this is happening? ...

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

I'm encountering a CastError while attempting to delete data in mongodb using Id

Encountered an issue while attempting to delete a MongoDB entry using the 'findByIdAndRemove' function in Mongoose. Specifically, it is throwing a 'Cast to ObjectId failed for value error'. Delete Service routes.delete('/:id' ...

Avoiding substantial sections during execution of the command "Npm run build"

Encountering an issue when attempting to execute "npm run build" (!) Encountered chunks larger than 500 KiB after minification. Suggestions: - Implement dynamic import() for code-splitting the application - Utilize build.rollupOptions.output.ma ...

How can you effectively update the content of a Parent component in react-native by communicating with its child component?

In one of my child components, I have included a button for interaction. Now, within my Parent component, I have three of these child components arranged side by side. Whenever any of these child components are clicked/touched, I want to trigger changes ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

How can I verify the number of completed form fields?

I seem to be facing a minor issue: I have a webpage where users can input information into up to 10 fields. However, they are not required to fill out all 10 fields. Initially, the user is presented with only one field, and they have the option to add mor ...