What are the steps to integrate live search functionality into VueJS applications?

I am looking to implement a real-time search feature on my Twitter clone in order to locate other registered users. These users are stored on the backend using Firebase.

The users are located on the backend, and here is an example of the search functionality that I want to achieve.

This is what I have attempted so far:

<script>
    export default {
      data() {
        return {
          search: "",
          users: ['Dummy', 'Users', 'From', 'Backend'],
        };
      },
      methods: {
        findUser(){
            const result = this.users.find(user => user.includes(this.search))
            console.log(result)
        },
      },
    };
    </script>

Can anyone point out what mistake I might be making?

Answer №1

In my opinion, utilizing a computed property in this scenario would be more advantageous for observing the "real-time" changes and implementing a .filter to extract the filtered list that matches the search keyword:

new Vue({
  el:"#app",
  data() {
    return {
      search: "",
      users: ['Dummy', 'Users', 'From', 'Backend'],
    };
  },
  computed: {
    filteredUsers(){
      return this.users.filter(user =>
        user.toLowerCase().includes(this.search.toLowerCase())
      );
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="search"/>{{filteredUsers}}
</div>

Answer №2

To perform real-time search using an API, consider utilizing WATCH functionality

This method can be implemented for sorting data on FIREBASE platform, more details can be found at https://firebase.google.com/docs/database/web/lists-of-data

var myUserId = firebase.auth().currentUser.uid;
var topUserPostsRef = firebase.database().ref('user-posts/' + myUserId).orderByChild('starCount')

The provided code snippet might have some discrepancies, but the core concept is communicated

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="search"/>{{filteredUsers}}
</div>
new Vue({
  el:"#app",
  data() {
    return {
      search: null, 
      users: []     
    };
  },
  computed: {
    filteredUsers(){
      return this.users.filter(user =>
        user.toLowerCase().includes(this.search.toLowerCase())
      );
    },  
  },
  watch: {
      watchUser(search) {
       if (search) {
       this.searchPerson()
      }
    },              
 },
 methods: {  
   searchPerson() {
        this.loading = true;
        this.fetchUsers()
          .then(res => {
            this.users = normalizeResponse(res)
            this.loading = false          
          })
      },
      fetchUsers() {
        return axios({
          method: 'get',
          url: '',
          params: {        
          },
          headers: {
            'Content-type': 'application/json'
          }
        });
      },
    }
 });

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

guidelines for splitting content into A4 size pages automatically using Vue

Hey there, I'm dealing with the issue of overflowing content not fitting on the next A4 page. My situation: I'll begin with a single A4 page When the content from the previous A4 page overflows, I want the remaining content to move to the next ...

The intricacies of converting AudioBuffers to ArrayBuffers

I currently have an AudioBuffer stored on the client-side that I would like to send through AJAX to an express server. This link provides information on how a XMLHttpRequest can handle sending and receiving binary data in the form of an ArrayBuffer. In m ...

Issues with uploading files on iOS devices when using ReactJS

Encountering an issue with uploading photos on iPhone in a Reactjs app. The problem seems to be specific to iOS as the code works fine on Android and computer. Below are the codes for better debugging. "use client" import Link from "next/l ...

Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows: Form Component: Responsible for adding items to the to-do list Item Component: Represents individual to-do items App Component: Contains a *ngFo ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

The incompatible peer dependency of node.js is causing issues with running npm update

C:\Users\Projects\webapp +-- UNMET PEER DEPENDENCY <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6012050103142051554e544e52">[email protected]</a> `-- UNMET PEER DEPENDENCY <a href="/cdn-cgi/l/e ...

Leverage TypeScript Enum along with PropTypes to declare the properties of a React component

Upon having the Component and utilizing a TypeScript Interface for defining its props: interface Props { headerType: DROPDOWN_MENU_TYPE, //DROPDOWN_MENU_TYPE is enum headerContent: SVGClass isReverse: boolean; }; const MyComp: React.FunctionC ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Enabling a checkbox grid for exclusive rectangular selections

Apologies for the confusing title, I struggled to come up with something more fitting. Let's say my client needs a square area on their homepage where they can upload images that will be placed within various boxes in a grid. The available box optio ...

Error in custom class using vanilla JavaScript: "Error: Unable to assign innerHTML to an undefined property"

Apologies for the ambiguous title, but I am struggling to pinpoint the exact issue at hand... I'm essentially guessing my way through this problem. This marks my initial venture into creating a reusable Javascript class. Below is a simplified version ...

Generating Vuetify badges and icons with createElement in the render function: A step-by-step guide

Within my Vue application, I utilize a v-data-table. The column values are generated using a render function within a functional component as illustrated below: render(createElement) { if (this.$props.format) { return this.$props.format(this.ite ...

How can I trigger a JavaScript function when the ENTER key is pressed?

I'm attempting to use JavaScript to scroll down a page. The code below works perfectly when I use javascript:pageScroll() in a link or button: <SCRIPT LANGUAGE="Javascript"> function pageScroll() { window.scrollBy(0,50); // hor ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

What are the benefits of implementing a hexadecimal strategy in javascript?

I have a somewhat unusual question that has been puzzling me. I've noticed some interesting choices in naming variables in JavaScript, seemingly using what appears to be "a hexadecimal approach". For example, I see variables named like _0x2f8b, _0xcb6 ...

Issues with Pageinit and Ready Event Timings

Check out this fiddle where I am experiencing an issue related to pageinit and ready events In the fiddle, everything functions properly using onLoad and onDOMready. This includes: The subject listings are loaded correctly with a popup displaying module ...

Autofill functions may not be compatible with input fields generated using JavaScript

Having trouble with browsers not using autocomplete in login overlays generated with JavaScript? It can be really annoying. Any suggestions on how to fix this issue? Should I create a hidden form within the original HTML and then move it into the overlay? ...

Organizing controllers in separate files within AngularJS

I've been working on modularizing an AngularJS project by implementing different controllers in their own JS files. However, I'm facing issues with getting them to work properly. Below is my config.js file where the primary module is defined: ( ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

Can anyone recommend an HTML element that is capable of containing spans and supporting editable text within?

Is there a way to combine a span or another container with editable text within the same box, such as one of the boxes on the left side? https://i.sstatic.net/ZBTtn.jpg I am looking to enable users to click directly on the box, input text, and then a ...

Creating a dynamic multidimensional array or object in AngularJS: tips and tricks

Below is the code snippet where I am attempting to dynamically construct an associative array in angularJs: $scope.details = {"profilesFound": [ "https: //twitter.com/alexandreagular", "https: //twitter.com/?profile_id=46130006", "https: //f ...