`Quasar V2 input field with autocomplete feature`

How can I add autocomplete functionality to a text-field in Quasar, where suggestions are fetched from a web service after entering at least 2 characters?

I noticed there was an autocomplete component in older versions of Quasar, but I couldn't find it mentioned in the current documentation:

There is also autocomplete support for q-select, but not for q-input:

Environment:

  • Vue 3.0.0
  • Quasar 2.6.0

Answer №1

To efficiently add auto-complete functionality, it is recommended to utilize the QSelect component instead of the text-field QInput.

Enhance Your Auto-Complete | Quasar Framework

QSelect Interactive Autocompletion Example:

<template>
  <div class="q-pa-md">
    <div class="q-gutter-md row">
      <q-select
        filled
        :model-value="dataModel"
        use-input
        hide-selected
        fill-input
        input-debounce="0"
        :options="dataOptions"
        @filter="performFiltering"
        @input-value="setSelectedValue"
        hint="Interactive Text Autocompletion"
        style="width: 250px; padding-bottom: 32px"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              No matches found
            </q-item-section>
          </q-item>
        </template>
      </q-select>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'

const suggestions = [
  'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle'
].reduce((acc, option) => {
  for (let i = 1; i <= 5; i++) {
    acc.push(option + ' ' + i)
  }
  return acc
}, [])

export default {
  setup () {
    const dataModel = ref(null)
    const dataOptions = ref(suggestions)

    return {
      dataModel,
      dataOptions,

      performFiltering (value, update, abort) {
        update(() => {
          const key = value.toLocaleLowerCase()
          dataOptions.value = suggestions.filter(item => item.toLocaleLowerCase().indexOf(key) > -1)
        })
      },

      setSelectedValue (value) {
        dataModel.value = value
      }
    }
  }
}
</script>

For scenarios where Lazy filtering is needed, like fetching suggestions from a REST API:

QSelect Delayed Filtering Sample:

<template>
  <div class="q-pa-md">
    <div class="q-gutter-md row">
      <q-select
        filled
        v-model="contentModel"
        use-input
        hide-selected
        fill-input
        input-debounce="0"
        label="Delayed Filter"
        :options="apiOptions"
        @filter="fetchDataSuggestions"
        @filter-abort="abortFetching"
        style="width: 250px"
        hint="Utilizing hide-selected and fill-input features"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              No content available
            </q-item-section>
          </q-item>
        </template>
      </q-select>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'

const apiOptions = [
  'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle'
]

export default {
  setup () {
    const contentModel = ref(null)

    return {
      contentModel,
      apiOptions,

      fetchDataSuggestions (query, update, abort) {
        // Use abort() if data retrieval fails

        setTimeout(() => {
          update(() => {
            if (query === '') {
              apiOptions = apiOptions
            }
            else {
              const keyword = query.toLowerCase()
              apiOptions = apiOptions.filter(item => item.toLowerCase().includes(keyword))
            }
          })
        }, 1500)
      },

      abortFetching () {
        // console.log('Delayed fetch aborted')
      }
    }
  }
}
</script>

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

Improving React's onClick Functionality for Better Performance and Reducing Re-render

Can the method of setting the isVisible state impact performance when dealing with two different divs? Specifically, does the ShowDiv approach recreate the function on each render? Is there any advantage to using ShowDiv2 over ShowDiv, or are they essenti ...

Creating Blurry Text Effects in HTML (Step-by-Step Tutorial)

I have a basic text that is centered inside the canvas. However, it appears blurry and unattractive. Can anyone suggest how to enhance its appearance? // Populate the signature canvas with data var canvas = document.getElementById("signatureCanvas"); v ...

A guide to showcasing the array index in a vuetify data table

I am working with a server response that includes an array of data passed to my Vue instance. I have successfully created a data table using this array, but I am unsure how to display the index of the array for a serial number. Below is a snippet of my co ...

Move the cache folder for NextJS to a new location

Is it possible to customize the location of the cache folder currently located in "./.next/cache"? I am interested in modifying this because I am developing an application that receives high traffic daily, and I plan to deploy multiple applications from m ...

Could there be a potential explanation for a 400 error in spite of successful testing in Post

I am currently experiencing an issue with the Deepl API. When I make a request using Postman, it is successful. However, when trying to use it in my app, I only receive a 400 Error response. I suspect that this may be due to incorrect headers setup, even t ...

Eliminate the space between the navigation bar and carousel when using Materialize with Vue.js and Laravel

I am facing an issue with the gap between the navbar and carousel in my materialize design. I have implemented Vue components for each div and Laravel as the backend. Using Sass for CSS preprocessing, I attempted to adjust the margins for the body, navbar, ...

Warning: Angular JS encountered a [$injector:modulerr] error

I'm currently working on developing an application using the MEAN stack. Here is a snippet of my controller code: var myApp = angular.module('myApp',[]); myApp.controller('AppCtrl',['$scope', '$http', function( ...

Issues with nodemon and nodejs in the Windows profile are causing functionality problems

Recently, I've been relying on nodemon utility to assist me with my nodejs development tasks. However, I encountered a problem after changing my profile on my Windows PC - now I can't seem to use nodemon at all... I tried reinstalling it using t ...

Sharing a PHP variable between different webpages by utilizing JavaScript

I'm attempting to transfer a PHP variable to another page utilizing JavaScript. Here is what I have tried so far: header.php: <script> var county = "<?php echo $county; ?>"; $.post("ajax.php",county); </script> ajax.php: ...

"JavaScript code for creating a dynamic switching effect in HTML

I currently have 4 divs on my webpage that can be hidden or shown using JavaScript when clicking the menu at the top of the page. Here is my current script: <script type="text/javascript"> function showHide(d) { var onediv = document.get ...

Unwillingness of Ajax to accept Names containing apostrophes as a parameter

$(".loadingPnl").removeClass('hdn'); var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/S ...

The draggable functionality is malfunctioning once the image is enlarged with Jquery

When it comes to creating a viewport function using jquery.viewport, I'm faced with the challenge of integrating it with jQuery UI slider and a custom zoom function for images. I've also utilized a plugin to enhance the viewport functionality. T ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Checking the current password using AngularJS and Laravel for custom validation techniques

I initiated an angular + laravel project yesterday, but I encountered an error in angular which has halted my progress. Below is the code snippet: <div class="form-group" ng-controller="CheckPawd"> <label>Current Password</label> &l ...

The function "onFinish" is utilizing the React Hook "useAxios", but it is not part of a React function component or a custom React Hook function

I'm currently working on a project using React and Ant Design. Here is the custom hook useAxios that I created: import { useState, useEffect } from 'react'; import axios from 'axios'; axios.defaults.baseURL = 'http://localho ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

Laravel modal causing video playback to continue even after closing

I have been working on creating a process where a video will play in a modal when clicked and then pause when the modal is closed. However, I have encountered an issue where the video continues to play even after the modal is closed. Here is the code I am ...

Implementing CSS styles with the className attribute in a Material UI component within a ReactJS application sourced from a dynamic JSON object

I have a dynamic JSON object that includes a button element. I am using createElement and Material UI to display the data from this object. I wanted to add custom CSS styling to the button component using className, but I've been struggling to achiev ...

What is the reason for the next function occurring after the component has been fully loaded in beforeRouteEnter?

When I trigger the beforeRouteEnter event, I initiate a promise/http call that takes a moment to retrieve some data. Once the data is obtained, I pass it to the result prop within the component using the next function. Additionally, there is a getter in ...