Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file:

    <template>
            <input value="Гарантийный случай"
                           v-model="searchText"
                           :class="{'w-autocomplete__input_completed': completed}"
                           ref="input"
                           @click="areOptionsVisible = !areOptionsVisible"/>

           

            <div v-if="areOptionsVisible"
                 :style="{maxHeight: maxHeight, overflow: 'auto', zIndex: zIndex}"
                 class="w-autocomplete__items">
                <div v-for="option in options" class="w-autocomplete__item_first" >
                    {{ option.name }}

                        <div v-for="item in option.children" class="w-autocomplete__item"
                            :class="{'w-autocomplete__item_active': currentIndex === item}"
                            @mouseenter="setActive(item)"
                             @keyup.up="changeCurrent('up', item)"
                             @keyup.down="changeCurrent('down', item)"
                             @click="doChoose(item)">
                            {{ item.name }}
                        </div>
                </div>
            </div>
</template>

<script>
    export default {
        name: 'dropdown',
        props: {
            placeholder: {
                type: String,
                required: false,
                default: '',
            },
            options: {
                type: Array,
                default(){
                    return []
                }
            },
        },
        data: function () {
            return {
                counter: 0,
                currentIndex: null,
                completed: false,
                chosenItem: null,

                areOptionsVisible: false,

                searchText: '',

                data: [],

            }
        },
        computed: {
            filteredOptions(){
                return this.props.options.filter(elem => {
                    return elem.name.toLowerCase().includes(this.searchText.toLowerCase());
                });
            },
        },

        .......
    }
</script>

This is how I pass the array to this list in another file:

 <template>
  ........

  <div class="complaint-form__line-item">
                <div class="form-group">
                    <label>Гарантийный случай</label>
                    <dropdown  :options="options" />
                </div>
             </div>
 ........
</template>



<script>

    ........

    export default {
        name: 'complaint-form',
        components: {LockedImport, UploadFiles, CarNumberInput, Autocomplete, Dropdown},
        props: {
            ......
            }
        },
        data() {
            const complaint = new Complaint();

            return {
                ........

                options: [
                    {name: 'Выход детали из строя в процессе эксплуатации', value: null,
                        children: [{name: 'Увеличение зазора, люфт (дробь/стуки)', value: 53},
                                    {name: 'Обрыв детали', value: 54}]},

                    {name: 'Поломка при установке', value: null},

                    {name: 'Брак до установки', value: null,
                        children: [{name: 'Недокомплект', value: 55},
                                    {name: 'Заводской брак (замятия, отсутствие резьбы, пробой пыльника и т.д.)',
                                        value: 56}]},

                ],

            }
        },

Why isn't the computed function working correctly? After adding it, the list does not show up at all when clicking on the field as expected. It seems that there is a breakdown in functionality. My intention is to apply filtering based on the text entered in the input field.

Answer №1

To ensure proper functionality, Vue.js does not allow for more than a single element inside a <template> tag. For the dropdown component, it is recommended to enclose the entire code within a <div> tag or a similar container.

Additionally, it may be beneficial to utilize the focus event instead of the click event for the input. This will prevent the dropdown from remaining visible when not actively focused on the input field.

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

React Native: Struggling with Button Styling

I am relatively new to React Native, although I have experience with React in my professional work. I'm finding that applying styles to components in React Native is a bit different than what I'm used to. Specifically, I am struggling to apply s ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

Encountering the error message "Vue CLI service command is not recognized" while attempting to run a Vue application

When I run the following commands in the root directory of my Vue app (version 2.6.12) rm -rf node_modules npm install npm run serve An error occurs with the message: sh: vue-cli-service: command not found To resolve this issue, I have to manually crea ...

Guidelines for transferring JavaScript array data to a csv file on the client side

Despite the abundance of similar questions, I am determined to tackle this using JavaScript. Currently, I am utilizing Dojo 1.8 and have all attribute information stored in an array structured like this: [["name1", "city_name1", ...]["name2", "city_name2" ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

Issue with AMCharts: DateAxis on my XY graph unexpectedly zooms out to the year 1970 when stacked

Currently, I am attempting to display multiple processes throughout a single day on an AMChart XY axis. Everything seems to be functioning correctly initially, but as soon as I stack the data, the timeline unexpectedly zooms out all the way to 1970. Howev ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

There is an issue with the function of elem.autocomplete - it is not recognized

I'm new to Angular.JS and have been struggling for the past 6 hours. I've been working on reading data from an HTTP source and displaying it as an autocomplete feature on the view. Previously, the data was displayed in a select box, but I decide ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Consolidate all scripts into a single file with Asp.net MVC 5 bundling

On one of my razor pages, I have the following script section: @Scripts.Render("~/bundles/script1") @Scripts.Render("~/bundles/script2") @Scripts.Render("~/bundles/script3") The issue is that it renders three separate JavaScript files. Is there a way to ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

Guide to running a NextJS app alongside an Express server backend on the same localhost port

I'm working on hosting my NextJS app, which is built with React, on the same localhost port as my express api-server backend. Within my express server API settings, I have configured my API server to listen on: http://localhost:3000/graphql How can ...

Enhance filtering capabilities in ng-repeat by adding controls

After utilizing ng-repeat to display some JSON data, I have incorporated form controls to filter output data from another JSON file. Here is a simplified example: First JSON data: var technologies = [ {"id":"5", "slug":"mysql", "label":"MyS ...

Ways to eliminate redundant older React components within a different library

Having trouble with material-ui in my React project as I encounter this error. Error: Invalid hook call. Ensure hooks are only called inside the body of a function component. Check for: Possible mismatch of React and renderer versions (i.e., React DOM) ...

Sharing data across multiple paths

route.post('/register',function(req,res){ //completed registration process // token value assigned as 'abc' }) route.post('/verify',function(req,res){ // How can I retrieve the token ('abc') here? }) I' ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

Traversing through JSON main sections, checking for operation and subsequently retrieving data

I have a json structure below: { users: [ { action: 'add', payload: [Array] } ], categories: [ { action: 'add', payload: [Array] } ], products: [ { action: 'add', payload: [Array] } ] } Can you suggest a method using .m ...