Guide to showcasing the most recent search history results upon clicking the search button in vuejs?

My JavaScript file is displayed below:

<div v-bind:class="{'open':openSuggestion}" class="search-bar">
    <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"
    />
     <ul v-for="(user, i) in filteredUsers" :key="i" class="autocomplete-results"
      v-show="isOpen" :class="{ 'is-active': i === arrowCounter }">
      <li @click="setResult(user.text)">{{ user.text }}</li>
    </ul>
    <span v-if="isSearchText" class="close-icon" @click="clearSearch"></span>
    <!--<i class="fa fa-times-circle-o" aria-hidden="true"></i>-->
    </div>
    <button type="button" class="btn btn-primary search-icon">
        <i class="fa fa-search"></i>
    </button>
    </div>

export default {
    name: 'searchBar',
    data() {
        
        return {
            users: [{
                id: 1,
                text: "Stainlrs",
                done: false
              },
              {
                id: 2,
                text: "Alum Bars",
                done: false
              },
              {
                id: 3,
                text: "BrBars",
                done: true
              },
              {
                id: 4,
                text: "Oil",
                done: true
              }
            ],
            search: '',
            arrowCounter: -1,
            isOpen: false,
            filteredUsers: [],
        
            open: false,
            current: 0,
            value: '',
            isSearchText: false
    }
    },
 props: {
        suggestions: {
            type: Array,
            required: true
        },

        selection: {
            type: String,
            required: true,
            twoWay: true
        }
    },


    methods: {
        setResult(text) {
            this.search = text
          },
        enter() {
            this.selection = this.matches[this.current];
            this.open = false;
        },

    

        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);
            }
          },

          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)
          },

      
    
        change() {
            if (this.open == false) {
                this.open = true;
                this.current = 0;
            }
            
            
            if(this.search == "") {
                this.isSearchText = false;
            } else {
                this.isSearchText = true;
            }
            
        },

    

        clearSearch(i) {
            if(this.search != "" ){
                this.search = "";
                document.getElementById("SearchText").value = "";
                this.isSearchText = false;
            }
            
        }
    }
  };

I am currently developing a search filter using Vue.js. One issue I am facing is that I want to display recent search history instead of showing all JSON data in the recent search section.

When I begin typing, the filter should retrieve data from JSON and upon clicking the search button, it should display the recent search history.

Answer №1

To enhance user experience and ensure search persistence across sessions, I suggest utilizing the localStorage feature. By storing search data in localStorage, you can easily access it from any part of your application. This method is particularly beneficial if the only information you need to save for later is related to searches. Each time a search is performed, add the search text to an array that is then saved in localStorage. This allows for quick retrieval of past searches and helps manage the amount of data stored in the search history.

methods: {
    onEnter: function () {
      let storedSearches = this.storedSearches;
      if (!storedSearches.includes(this.input)) {
        storedSearches.push(this.input);
        localStorage.storedSearches = JSON.stringify(storedSearches);
      }
    },
  },
  computed: {
    storedSearches: function () {
      return localStorage.storedSearches === undefined
        ? []
        : [...JSON.parse(localStorage.storedSearches)];
    },
  },

Answer №2

Ensuring accurate translations in your summaryConversation method is crucial. The key steps to follow include verifying the retrieval and utilization of translations. It is important to double-check translation keys and files to confirm their proper definition and placement within the directory to avoid any missing translations.

Answer №3

My primary objective is to implement autocomplete functionality for INPUT tags in VUEJS.

I achieved this using the HTML <datalist/> element and leveraging VUEjs with Client-Side Storage.

  1. VueJS Implementation
<b-col sm="5" md="6" class="my-1">
<b-input-group>
 <b-form-input v-model="filter" name="filter" list="my-list-id" type="search"
                      placeholder="MAWB NO ...">
 </b-form-input>
 <datalist id="my-list-id">
      <option v-for="size in storedSearches">{{ size }}</option>
 </datalist>
 <b-input-group-append>
   <b-button :disabled="!filter" @click="addStoredSearches">Search</b-button>
 </b-input-group-append>
</b-input-group>
</b-col>
  1. Script Code -
data: () => ({
    filter: null
}),
computed: {
        storedSearches: function () {
            return localStorage.storedSearches === undefined
                ? []
                : [...JSON.parse(localStorage.storedSearches)];
        },
    },
methods: {
    addStoredSearches() {
        let storedSearches = this.storedSearches;
        if (!storedSearches.includes(this.filter)) {
        storedSearches.unshift(this.filter);
        localStorage.storedSearches = JSON.stringify(storedSearches);
        }
    }
}

References: https://v2.vuejs.org/v2/cookbook/client-side-storage.html https://www.w3schools.com/tags/tag_datalist.asp

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

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

Align the Font Awesome icon and text in the middle vertically within an <a> tag/router-link

My b-button acts as a router-link/a tag, and I can't seem to get the content centered the way I want. I'm aiming for the text to be below my font awesome icon, with both elements aligned both horizontally and vertically, but nothing I've tri ...

Using the jqueryRotate plugin to rotate an image by 90 degrees

Is there a way to rotate images on a webpage using the JQueryRotate script? I have 10 images that I want to be able to rotate when clicked, but I'm not sure how to implement it. Any assistance would be welcomed. This is the HTML code for the images: ...

Promise of a repeating sequence of serial calls

I am looking to create a recursive serial call to the promise method times, which will return the result of calling the fn function N times and storing the results in an array. To achieve this, I have added a new attribute called results to the times func ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

unable to simultaneously scroll two elements

Within the realm of reactjs, I've crafted a function that smoothly scrolls elements by utilizing a useRef: ref.current?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); ...

Is there a way to automatically transfer the store's order value to my payment gateway's checkout process during the checkout process?

I am facing an issue with integrating the Razorpay payment gateway into my online store built on ecwid. The process involves decrypting order details from the store, sending them to the payment gateway for processing, and redirecting the customer back to t ...

You need to double click to successfully update the array in Vue/Vuex

Recently, I delved into Vue/Vuex and find myself at a loss with my current code. The method I trigger on click is as follows: Export (item) { this.exportObj = { start: this.dates[0], end: this.dates[1], userid: item.id, }; this.getAllByF ...

Issue: No default template engine specified and no file extension provided. (Using Express framework)

While I came across numerous questions with a similar title, they only provided me with partial help and did not completely resolve the error that plagued me. Just to provide some context, I had created a file named listing.js as a tool for running node c ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Having trouble retrieving JSON Data with PHP and Angular JS?

I am using AngularJS to fetch JSON-encoded data by passing an ID. Below is my controller: dhmsApp.controller('dhmsDetailsView',function($scope,$http, $routeParams){ $http.get("include/detailViewBg.php", {params: {id: $routeParams.id}}) .s ...

What is the method used to create the scrolling effect on this website?

I am in the process of creating my own personal website and I would like it to function similar to the following example: Instead of the typical scrolling, I'm interested in transitioning between different sections on the page. Could this be achieved ...

The react router threw an error, expecting an assignment or function call but instead receiving an expression

Within a Material Table, there is a button that triggers page routing through react routers to navigate to different URLs. The setup involves defining functions, calling the Material Table element <MuiTable>, and rendering a button below the table fo ...

How can I make a bootstrap offcanvas disappear in Vue 3 after clicking a router-link?

Hey there! I'm looking to close the bootstrap-5 Offcanvas when I click on a link inside it. Here's the code for the Offcanvas: //Button activate Offcanvas <button class="navbar-toggler" type="button" data-bs-toggle=&quo ...

Occasionally, wmuslider fails to load properly

I am currently developing a website for a dance studio and have implemented the wmuslider to create a slider on the homepage. However, I am encountering an issue where the slider does not consistently load. This seems to be a problem across different brows ...

Automatically collapse the Shadcn-UI Accordion when the mouse exits

For my self-education project, I am working on building a sidebar with an accordion using Shadcn-ui, NextJS (13.4), React, and Node. Being new to these technologies, I have encountered a problem that I can't seem to solve. The sidebar expands on mous ...

Is it possible to include a button in a search bar while maintaining the keypress functionality in Vue?

My search function is operational, but it currently requires the user to press the enter key to display results. I am interested in adding a button option for users as well. Users should be able to find results by either pressing enter or clicking the bu ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...

Using Vuex mapState does not activate the computed property

I am facing an issue with my V-Data-Table. The items in it are coming from a computed property that should be triggered when the mapState changes, but for some reason, it is not working as expected. Objective: I want the computed property to trigger whene ...