Experimenting with a customizable Vue.js autocomplete feature

Check out this sample code:

https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/

The following is the HTML code:

<div id="app">

<button type="button" v-on:click="displayVal()">Button1</button>

  <autocomplete v-model="nombre" :items="[ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear', 'Peach', 'Grape', 'Tangerine', 'Pineapple']" />

<button type="button" v-on:click="displayVal()">Button2</button>

</div>



<script type="text/x-template" id="autocomplete">
  <div class="autocomplete">
    <input type="text" @input="onChange" v-model="search" @keyup.down="onArrowDown" @keyup.up="onArrowUp" @keyup.enter="onEnter" />
    <ul id="autocomplete-results" v-show="isOpen" class="autocomplete-results">
      <li class="loading" v-if="isLoading">
        Loading results...
      </li>
      <li v-else v-for="(result, i) in results" :key="i" @click="setResult(result)" class="autocomplete-result" :class="{ 'is-active': i === arrowCounter }">
        {{ result }}
      </li>
    </ul>

  </div>
</script>

This is the JS section:

const Autocomplete = {
  name: "autocomplete",
  template: "#autocomplete",
  props: {
    items: {
      type: Array,
      required: false,
      default: () => []
    },
    isAsync: {
      type: Boolean,
      required: false,
      default: false
    }
  },

  data() {
    return {
      isOpen: false,
      results: [],
      search: "",
      isLoading: false,
      arrowCounter: 0
    };
  },

  // More methods and functions go here...

};

The CSS part looks like this:

#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
}

.autocomplete {
  position: relative;
  width: 130px;
}

// Styling for autocomplete and its results

How can I make sure that displayVal shows the selected value from autocomplete or the user input if it's not in the list? Also, how do I go about displaying Button2?

Answer №1

View the updated demo.

  1. Make sure to include

    this.$emit("input", this.search);
    in the setResult function for question 1.

  2. Add </autocomplete> at the end for question 2.

 <autocomplete v-model="name" :items="[ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear', 'Peach', 'Grape', 'Tangerine', 'Pineapple']" ></autocomplete>

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

The plugin "react" encountered a conflict while trying to sync with both the "package.json" and the "BaseConfig" files

Whenever I open Terminal in my react folder and try to start the react app using npm start, I always end up encountering an error on the browser. The error message states that the "react" plugin is conflicting between two paths: "package.json » eslint ...

Is it possible in RxJS to configure a ReplaySubject (or equivalent) that replays the latest messages with a distinctive identifier?

Is it possible to create a generic code that behaves like a ReplaySubject but emits each most recent message with a unique name upon subscribing? In the script below, the current output is... I want this to be logged once ... received the latest bbb 5 I c ...

Please refrain from displaying the POST response in Express

I have a simple Express API setup: app.get('/example', function(req, res) { if (req.body.messageid == 1) { res.send({message: "Message"}); } } The API returns a message to be displayed on an HTML page. To display the message, I created ...

Creating a personalized instance function in Angular's $resource

When working with AngularJS, all actions for a $resource are added as $customAction methods to the Resource. This allows me to easily invoke them as methods on resource instances. For example: var User = $resource('/user/:userId', {userId:' ...

How do prototype, the $.extend method, and the concept of "return this" all connect with each other?

I've been assigned a legacy project, and I find myself puzzled by the purpose of this code. define(['jquery', 'components/BaseComponent', 'bootstrap'], function( $, BaseComponent, bootstrap ) { 'use strict&a ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

What is the best way to compare the previous and next values in React?

When working with the code snippet below to send a list of values to another component - React.createElement("ul", null, this.state.stock.map(function (value){ return (React.createElement(Price, { price: value })) }) ) the values are then sent t ...

Execute asynchronous code in a Next.js component without relying on the UseEffect hook

Within my nextjs application, there is a StrapiImage component that takes in an image object from the strapi backend api as a prop. This component sets the width, height, URL, and any additional props for the image. Essentially, it serves as a shortcut for ...

Obtaining data from the following entry in JSON format using the Twitter API

I am currently developing a webpage that showcases user tweets, however I want to visually represent the gap in time between each tweet by displaying empty spaces. I have been struggling with the logic of how to achieve this task and haven't made muc ...

Enhance your Vuejs Project by incorporating the Vuetify data table component

Looking to integrate the Vuetify Data Table into my current Vuejs project. After installing globally with vue add vuetify, I need assistance on how to successfully implement it. Any guidance is appreciated. Thank you. Thanks ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

Mutation observer fails to observe an element if it is housed within a function

I am attempting to initialize the liveChatAvailable value as true and set the isLoading value to false once the crispClient element loads onto the page. However, when the observer object is placed within a function, the if (crispClient) code does not exec ...

Effective sparse translation between whole numbers

I am in the process of developing a specialized regular expression engine that utilizes finite automata. My goal is to manage numerous states, each equipped with its own transition table mapping unicode code points (or UTF-16 code units; I have yet to fina ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

The use of backticks within an HTML document for nesting purposes is not permitted

Currently, I am utilizing nodemailer to send HTML template code in Node.js. However, the issue I am encountering is that I cannot nest backticks within it: Here's my code snippet: let mailDetails={ from: 'example@example.com', to: & ...

TypeScript enabled npm package

I am currently developing a npm module using TypeScript. Within my library, I have the following directory structure: . ├── README.md ├── dist │ ├── index.d.ts │ └── index.js ├── lib │ └── index.ts ├── ...

How can jQuery be utilized to dynamically update the text in a navbar?

<div id="page1" data-role="page"> <div data-role="header" data-position="fixed" align="center"><img src="img/VAWE-long-300x30-transparent.png" width="300" height="30" alt="" /></div> <div data-role="content" style="margin ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...

What is the reason behind the absence of certain fontAwesome icons?

I'm having trouble connecting Font Awesome in Vue.js ************* import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import { faVuejs } from '@fortawesom ...

Verify if a personalized angular directive is able to display or conceal an element

I have a custom directive that toggles the visibility of an element based on the value of another service. I attempted to write a test to verify if the directive functions as intended. Initially, I used the ":visible" selector in my test, but it consistent ...