Receive various elements at once rather than just one. These elements are generated from a set of options in vue.js

My task involves creating a list of musical instruments that triggers an auto-suggest feature in a c-input component when users start typing. Additionally, I need the ability to dynamically add or remove the auto-suggest functionality from the c-input component.

/* instrument component */

<template>
    <c-input ref="input"
      :values="inputValue"
      :placeholder="placeholder"
      @input="onInput"
      @change="onChangeInput"
      @reset="reset" />
    <autosuggest
      v-if="showSuggests"
      :inputValue="inputValue"
      :suggests="suggests"
      @onSelectRic="selectRicFromList"
    ></autosuggest>
  </div>
</template>

<script>
  export default {
    name: 'instrument',
    data: () => ({
      suggests: [],
      inputValue: '',
    }),
    computed: {
      showSuggests() {
        return this.isNeedAutosuggest && this.showList;
      },
      showList() {
        return this.$store.state.autosuggest.show;
      },
      isloading() {
        return this.$store.state.instruments.showLoading;
      },
      defaultValue() {
        if (this.instrument.name) {
          return this.instrument.name;
        }

        return '';
      },
    },
    [...]
  };
</script>

I'm dealing with a parent component that looks like this:

<template>
  <div>
    <instrument v-for="(instrument, index) in instruments"
          :key="instrument.name"
          :instrument="instrument"
          :placeholder="$t('change_instrument')"
          :isNeedAutosuggest="true" /> <!--that flag should manage an autosuggest option-->
    <instrument v-if="instruments.length < maxInstruments"
          ref="newInstrument"
          :isNeedAutosuggest="true" <!-- here too -->
          :placeholder="$t('instrument-panel.ADD_INSTRUMENT')" />
  </div>
</template>

The issue I am facing is that for each instrument in the list, there is a corresponding auto-suggest component displayed in the DOM. Ideally, there should only be one auto-suggest component active at a time based on certain conditions. Moving the auto-suggest functionality to the parent level is not ideal due to flexibility concerns and its close association with the c-input element.

Do you have any suggestions on how to address this?

[UPDATE]

This is how I resolved it:

I created a separate wrapper component that encapsulates both the input and auto-suggest components. If an input requires auto-suggest functionality, this wrapper component is used; otherwise, a simple input component is utilized.

/* wrapper.vue  - inserted into Instrument.vue */
<template>
  <span>
    <fc-input ref="input"
      :values="value"
      :placeholder="placeholder"
      :isloading="isloading"
      @input="onInput"
      @changeInput="$emit('change', $event)"
      @resetInput="onResetInput" />
    <fc-autosuggest 
      v-if="isSuggestsExist"
      :suggests="suggests"
    />
  </span>
</template>

Answer â„–1

If you want to achieve this functionality, consider implementing a function within each instrument component that calls the parent component and searches for the first instance of the instrument component in order to locate the autosuggest. This function could look something like:

name: 'instrument',
...
computed: {
    autosuggestComponent () {

        // This is just pseudo code
        const parentChildrenComponents = this.$parent.children();
        const firstChild = parentChildrenComponents[0];
        const autosuggestEl = firstChild.$el.getElementsByTagName('autosuggest')[0];

        return autosuggestEl.__vue__;
    }   
},
methods: {
    useAutosuggestComponent () {
        this.autosuggestComponent.inputValue = this.inputValue;
        this.autosuggestComponent.suggests = [{...}];
    }
}

While this solution may not be the most elegant, it does allow for the encapsulation of logic within the instrument component.

Alternatively, I recommend creating a parent component that houses all the instrument components and interacting with the autosuggest through the parent. By creating an autosuggest component in the parent and passing it down to the child instrument components, you can ensure flexibility. If an instrument component does not receive a link to an autosuggest, it can create one internally, enabling its usage under different circumstances.

Feel free to reach out if you need further clarification on my suggestion.

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

Which cultural background is associated with the javascript Date object?

I recently noticed that my OS (Windows) and browsers are all set to Danish language. While attempting to parse a date in the Danish format (dd-MM-yyyy) using the following code: var x = "18-08-1989" var date = new Date(x); I realized that JavaScript was ...

Incorrect output when converting JSON to DataTable for Google Visualization

I am attempting to generate a chart using Google Visualization from a CSV file. After parsing the CSV file with PHP, I have extracted the required data in Json format. Specifically, Column 1 contains dates formatted as "dd/mm/yyyy" and Column 2 contains pr ...

Create and display a URL on a webpage using information entered into an input form

I am looking to create a URL that is generated from two input fields by the user, displaying the final URL within the same document instead of opening it in a new window. After reviewing this question, I want to modify the functionality so that the genera ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...

Point of View in ThreeJS Camera

When working with ThreeJS, I need to determine how to find the coordinate of a point that is exactly 1 unit in the direction the camera is facing, even when the camera is rotated at various angles. The rotation angles in ThreeJS can be quite confusing for ...

Ways to broaden the map of a variable in SCSS

Currently, I am utilizing a package known as Buefy, which acts as a Vue.js wrapper for the Bulma CSS framework library. Within Buefy's template components, there is an attribute/property called type (e.g., type="is-warning"). According to the document ...

Google Maps Autocomplete Feature Excludes Information on Atmospheric Conditions

Currently, I am utilizing the Google Maps Places Autocomplete Javascript API to enable users to choose a location by searching for the address or name of an establishment. Here is an example code snippet: autocomplete = new google.maps.places.Autocomplet ...

What is the best way to retrieve the browser language using node.js (specifically express.js)?

element, consider the scenario where a user requests a specific page and you are interested in determining the language set in their browser on the server side. This information is crucial as it enables you to customize the template with appropriate messa ...

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

Got lost after browsing and lost track of the reference window

I have successfully created a new browser window called win when the element with id #new-window-id is clicked. I have also set up an events system for that window, such as detecting if win.closed. Everything works fine until I navigate to links inside the ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

Instructions for automating the clicking of a Vue/Vuetify card using Selenium with Python

Currently, I am utilizing selenium version 4.0.0 for my project. I encountered a challenge while attempting to click on a Vuetify card element serving as a button. However, I kept encountering errors such as element not interactable: [object HTMLDivElemen ...

Ways to showcase a numeric value retrieved from an API on my webpage?

Greetings, esteemed guest! You are visitor number <span id=VisitorCounter></span> <script> fetch("https://unique-api-source.com/visits/getvisitorcount", { method: "GET", // mode: "cors", headers: { ...

To determine if all values in an array are true strings in Javascript and return a boolean true, stop checking as soon as a false string is encountered

I have an array var myarr = ["true","false","true"]; I am trying to get a boolean value of false from the above array. var myarr = ["true","true","true"]; And for this second array, I need a boo ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...

What is the best way to control the number of pages displayed in pagination?

I have implemented a pagination component in React, but encountered an issue where all pages were being displayed, causing the page to expand and require horizontal scrolling. Is there a way to limit the display to only 20 pages while still allowing for mo ...

Enhance multiple select functionality

I am currently working on a function to dynamically update the options in a select input based on the selection made in another select input. Specifically, when Method1 is selected, I want only the options 1A, 1B, and 1C to appear in the second select. S ...

How to activate a media query in response to user interaction using JavaScript

My responsive web page has various designs for different screen sizes, implemented using @media queries. I am interested in allowing users to manually adjust the design for smaller or larger screens without actually changing the screen size. Is there a wa ...

Creating HTML elements using JavaScript's Document Object Model

I am trying to create an img tag dynamically using JavaScript with the following code: <img id="drag0" src="http://localhost:34737/Images/MainSlider/A(1).jpg" class="col-4" draggable="true" ondragstart="drag(event)"> and I have a drag method setup ...