"Unlocking the potential of vselect in Vue.js: mastering the art of rendering elements in a

I have a Vue.js form with select drop-downs, and I am attempting to utilize the library to achieve this. According to the documentation, I need to pass an array into it, and I'm using an axios method to fetch the options for the drop-downs. The data that I am receiving is in the following format:

https://i.sstatic.net/DUEtW.png

With the following description:

https://i.sstatic.net/nbIpb.png

I only want to display the names in the options and retrieve the values as the ID of the respective row. How can I accomplish this?

My code looks like this: https://jsfiddle.net/eemdjLex/1/

<div id="app">
  <v-select multiple :options="model.data"></v-select>
</div>

import vSelect from 'vue-select';

Vue.component('v-select', vSelect)

const app = new Vue({
    el: '#app',
    router: router,
    data () {
        return {
            model: {},
            columns: {}
      }
    },
    methods: {
        fetchIndexData() {
                var vm = this;
                axios.get('/companies').then(response => {
                Vue.set(vm.$data, 'model', response.data.model)
                Vue.set(vm.$data, 'columns', response.data.columns)
            }
    }
});

It's not working properly, but it gives you an idea of what I'm trying to achieve.

Answer №1

In the case of using v-select with v-model, it seems that the entire option is returned as the value. To address this, a pair of computed values can be utilized.

new Vue({
  el:"#app",
  data:{
    serverData,
    selected: null
  },
  computed:{
    // Utilize serverData to create options with labels and values
    selectOptions(){
      return this.serverData.map(d => ({label: d.name, value: d.id}))
    },
    // selectedOption computes the id value of the selected option
    selectedOption(){
      if (this.selected)
        return this.selected.value
      else
        return null
    }
  }
})

Check out the example here.

Answer №2

Upon reviewing the information presented in the README on the GitHub repository for vue-select, it appears that the <v-select> component can be provided an array of objects containing label and value keys through the options property.

To achieve this, I suggest creating a computed property to format the model.data in the required structure:

computed: {
  options() {
    let data = this.model.data;
    let options = [];

    // Perform necessary formatting to transform the data into objects like: 
    // options = [{ label: 'foo', value: 1 }, { label: 'bar', value: 2 }]

    return options;
  }
}

Once the computed property is set up, you can simply pass it to the <v-select> component like so:

<v-select multiple :options="options"></v-select>

Answer №3

If you're looking for guidance on how to create a v-select component, you may find the official select docs helpful.

Here is an example of how your v-select component could be structured:

new Vue({
  template: `
     <select v-model="selected">
       <option v-for="option in options" v-bind:value="option.value">
         {{ option.text }}
       </option>
     </select>
     <span>Selected: {{ selected }}</span>`,
  el: 'v-select',
  props: [ 'options' ],
  data: {
    selected: ''
  }
})

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

Display a different string from an array at random, revealing each one gradually with a time delay

Looking for a way to display strings randomly without replacing one with another? I need a script that can shuffle words in a list and present them in a random order, with the ability to adjust the delay between each word. If you have a more effective code ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

`Incorporating dynamic link filtering in vis.js`

Can links and nodes be filtered in a vis.js network? I have configured a DataSet for both nodes and edges as follows: function drawNetwork(container){ var nodes = new vis.DataSet(); populateNodes(nodes); // implementation details skipped ...

Sending information from controller to directive in angularjs

I'm currently facing an issue where I am attempting to send data from a controller to a directive in order to dynamically update rows in a table. However, despite my efforts, the table does not reflect any updates and there are no error messages displ ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

How to accurately incorporate the "HH:MM" time format into a Date Object in JavaScript

I need to convert a specific time of the day into a Date Object. The time is in String format and is in CET (Central European Time). In CET, "16:00" translates to "15:00" in UTC during Winter time. The code snippet below achieves this conversion in node.js ...

"When attempting to upload an image from the front end, the issue arises that req.file

I have been troubleshooting this issue by referring to similar posts, but I am still facing the problem of getting 'undefined' when using console.log. I have followed instructions for defining the multer middleware from other sources, so I am uns ...

Error message from Firebase cloud function: We are unable to find a user record associated with the provided identifier

I am encountering an error when attempting to setCustomUserClaims in a trigger function. https://i.sstatic.net/QrLBT.png Here is the code snippet causing the issue: exports.onCreateCompaniesByUserFunction = functions.firestore.document('/com ...

Issues with routing in Node.js using Express

This is my first attempt at programming. I am currently in the process of setting up routing in the following way: var indexRouter = require('./routes/index'); var loginRouter = require('./routes/login'); app.use('/', indexRo ...

How can I show a dynamic popover with specific content when a "Copy" action is triggered?

I am attempting to copy a value to the clipboard: /** * If the browser does not support direct clipboard manipulation, use an alternate method * This is used in the copyTextToClipboard function. * * Function found at: https://stackoverflow.com/a/3 ...

Shader customization and dynamic window resizing with Three.js

Having trouble with resizing the Three.js shader scene using ThreeX to handle window resizing and changing orientation on mobile devices. When the window width is decreased, everything works perfectly. However, expanding the window either in width or heigh ...

What is the functionality of this JavaScript code after the "if" statement?

I am having trouble understanding how this code works, especially after the if(y in hash) statement. I don't see any values being pushed into hash initially. Can someone explain what happens behind the scenes and the significance of y in hash? var ...

Modifying a Field's Value by Referring to a Different Field

I am working on developing a form that includes a dropdown menu for changing the aircraft type. Additionally, I want to incorporate another field named "Registrations" which will automatically update the available registration options based on the selected ...

Using React.js to Retrieve Data from the Server without AJAX Calls

Currently, I am in the process of creating a web application using Express.js for the back-end and React.js for the front-end. Prior to using React.js, I utilized EJS templating and followed a similar workflow on the back-end as shown below: var express = ...

Accept two parameters for password change

Is there a way to include two values, one being the selected value and the other a PHP variable, in a dropdown select element's onChange function? For example: <div> <?php $sql4 = "SELECT DISTINCT (color), id ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

Elements are automatically removed from default.vue once they have been compiled in Nuxt

Looking to add a header in my Nuxt application within Nuxt/layouts/default.vue <template> <div> <Navigation/> <Nuxt /> </div> </template> But the code: <template> <Nuxt /> </template> ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

Unexpected server failure due to a new error occurring in the asynchronous authentication login function

This problem is really frustrating... I'm having trouble with a throw exception that causes my express server to crash in my async login function. The issue here is that the error isn't caught by the try/catch block. Even though the user data is ...