Enable Vue2 Select Component to accept a variety of arrays for selection choices

I am currently developing a customizable Select component that can be used with any Array provided as options.

It is working well when the object properties in the array have the same names bound in the component. However, if an array of objects with different property/attribute names is passed, the options do not render as expected. Is there a way to specify on the component which object property should be used as the option value and which as the option label?

FormSelect.vue / Component

<template>
   <select :id="id" v-model="selected">     
      <option v-if="options.length > 0" value="">Please Select</option>
      <option
        v-if="options.length > 0"
        v-for="(option, index) in options"
        :key="index"
        :selected="selected"
        :value="option.value"
        v-text="option.name"
       />  

    </select>
</template>
<script>
props: {
 value: {    
      type: [Array, String, Number, Object],
      default: null
    },
 options: {
      type: Array,
      default: () => []
    }
},

computed: {
    selected: {
      get() {
        return this.value ? this.value : "";
      },
      set(v) {
        this.$emit("input", v);
      }
    }
  }
</script>

Parent.vue / Parent

<form-select
   id="gender"
   label="Gender"
   :options="genderOptions"
   @input="handleEdit(deep(profile))"
   v-model="user.gender"
/>

This works:

genderOptions: [
  { name: "Male", value: "MALE" },
  { name: "Female", value: "FEMALE" }
],

This would not work (notice the object key names):

genderOptions: [
    { id: "Male", gender: "MALE" },
    { id: "Female", gender: "FEMALE" }
 ],

Therefore, there is a need to indicate to the component which properties should be used as the option value and label. It could be something like this, but it would also need to be handled on the component side:

<form-select
   id="gender"
   label="Gender"
   :options="genderOptions"

   optionVal="gender"
   optionName="id"

   @input="handleEdit(deep(profile))"
   v-model="user.gender"
/>

Answer №1

Ensure you include the optionVal and optionName props in your component and utilize them accordingly. Here is a suggested solution:

<script>
props: {
 value: {    
      type: [Array, String, Number, Object],
      default: null
    },
 options: {
      type: Array,
      default: () => []
    },
optionVal:{
    type:String,
    default: 'value'
    },
optionName:{
    type:String,
    default: 'name'
    }
},

computed: {
    selected: {
      get() {
        return this.value ? this.value : "";
      },
      set(v) {
        this.$emit("input", v);
      }
    }
  }
</script>
 <select :id="id" v-model="selected">     
      <option v-if="options.length > 0" value="">Please Select</option>
      <option
        v-if="options.length > 0"
        v-for="(option, index) in options"
        :key="index"
        :selected="selected"
        :value="option[optionVal]"
    v-text="option[optionName]"
       />  

    </select>

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

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

ES5 compatibility issue with Vue.js export default

I'm currently in the process of building a website, and I've decided to use Vue with ES5 for some parts. One issue I've encountered is trying to pass data from a child component in Vue back up to the parent. The solution proposed to me was ...

What steps should I take to activate JavaScript type checking in Vue files within Visual Studio Code?

After much exploration, I have successfully configured Visual Studio Code to perform type checking for JavaScript within JS files. This feature highlights any bad code and provides explanations for why it is considered as such here. However, this function ...

How to remove outer quotes from JSON data in Reactjs after using JSON.stringify

When using JSON.stringify on a Json data, I noticed that the resulting string includes double quotes at the beginning and end. For example: x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}} After using JSON.stringify, the result looks like t ...

Activate the active class on the icon when hovering over a dynamically generated span using Vue

Is it possible to activate multiple music notes when hovering over one? For example, if I hover over music note 2, both note 1 and note 2 should get active classes. And if I hover over note 3, then all three spans/icons should become active. I have succes ...

Could anyone please provide advice on how to resolve the issue I encountered when trying to make Post and get Http method calls using protractor?

I am currently facing an issue while trying to make a GET API request using protractor. The challenge lies in using the bearer token generated from a previous POST response in the headers of the GET request. Although I have successfully executed the POST r ...

Opt for utilizing a global npm package over repeatedly installing it

Is there a way to utilize the globally installed package without needing to reinstall it every time we run npm i? Here's the scenario I have: I've set up a docker image with a specific package already installed (installation command in the Docker ...

Using Javascript to retrieve information from a json file

I am currently working on incorporating JSON data into my script. I have noticed that when I manually declare a variable and check the console output, everything seems to work fine. <script> data = '[{"id": 1,"name": "Germany"},{"id": 2,"name": ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...

Tips on managing errors in a router with the help of middleware

Currently, I am utilizing node and express to create a server. However, there seems to be an issue where errors that occur within a router are not being properly handled, causing the entire server to crash: In my Server.js file: import SubRouter from &apo ...

Code for refreshing content using AJAX

I'm looking for AJAX code to set a value in a session. For instance: $_SESSION['verif_code'] I want to generate a random number and assign it to this session. I need some AJAX code to refresh this random number function and set the value ...

Increase the value of X within the given string

I am working on developing an application that transforms the initial string: 1.2.3.X Into multiple strings: 1.2.3.0 1.2.3.1 1.2.3.2 1.2.3.3 1.2.3.4 ...... This is a snippet of the code I have written so far: String.prototype.count=function(c ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

Manipulating the InnerHTML content of a total of 144 individual cells

I am currently developing a tile-based game using tables. Each td cell contains the following code: <td> <div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Attempting to install puppeteer within the Visual Studio Code terminal with financial support

I am having trouble installing puppeteer using the VSC terminal. Every time I try to run the npm install command, it doesn't download and prompts me about funding. Can someone please assist me with this issue? npm i puppeteer up to date, audited 67 p ...

Creating a range using v-for directive in Vue

For example: range(3, 5) -> [3, 4] range(5, 10) -> [5, 6, 7, 8, 9] I am aware that we can generate range(1, x) using v-for, so I decided to experiment with it like this: // To achieve the numbers in range(5, 10), I set (10 - 5) on `v-for` // and t ...

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...