How should v-select, item-text, and item-value be correctly utilized?

When I make an API call, the response is returned.

https://i.sstatic.net/AsFzu.png from another perspective.

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

I store the result of the API call in a variable called result = [];.

To create a dropdown list, I use v-select with :items="result".

If I want the services.name to be displayed as the text in the dropdown list and services._id to be stored in a variable using v-model, how should I set the item-text and item-value? The services._id will be used as the item-value.

I'm having trouble figuring out how to handle these nested properties.

Answer №1

You have the option to gather all the services from multiple sub arrays using a computed property.

This way, you will end up with just one array of objects (instead of an array of arrays within the services property) and can define the item-text and item-value properties!

Check out this sample code:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: () => {
    return {
      currentItem: null,
      items: [{
          services: [
            {_id: 1,name: 'foo'},
            {_id: 2, name: 'bar'}
          ]
        },
        {
          services: [
            {_id: 1,name: 'foo'}, 
            {_id: 3, name: 'baz'} 
          ]
        }
      ]
    }
  },
  
  computed: {
    allServices(){
      return this.items.reduce((acc, curr) => {
        curr.services.forEach(service => {
          if(!acc.find(x => x._id === service._id)) acc.push(service)
        })
        return acc
      }, [])
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b3d3e2e0b796533">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c1c2d2c3ded1cef78599819983">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a4a7b7a6bbb4ab92e0fce4fce6">[email protected]</a>/dist/vuetify.min.css" />

<div id="app" data-app>
  currentItem : {{currentItem}}
  <v-select v-model="currentItem" :items="allServices" item-text="name" item-value="_id"></v-select>
</div>

Answer №2

To customize the data displayed in a v-select, you can utilize its slots:

<v-select
    label="Services"
    v-model="customVar"
    :items="result"
    item-value="_id"
    item-text="name"
    return-object
  >
    <template v-slot:selection="data">
      {{ data.item.name }}
    </template>
    <template v-slot:item="data">
      {{ data.item.name }}
    </template>
  </v-select>

In addition, by using return-object as shown above:

This will modify the selection behavior to directly return the object instead of the value designated with item-value

This gives you the flexibility to select which variables to extract from the chosen object.

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

Toggle the visibility of images with input radio buttons

Explanation I am attempting to display an image and hide the others based on a radio input selection. It works without using label, but when I add label, it does not work properly. The issue may be with eq($(this).index()) as it ends up selecting a differ ...

Error: The meteor package encountered a SyntaxError due to an unexpected reserved word 'export'

I've made some modifications to a meteor package by adding this line: export const myName = 'my-package' However, I'm encountering an error: export const myName = 'my-package' ^^^^^^ SyntaxError: Unexpected reserved word I ...

Is it possible to enable auto play on HTML5 Video for iPad similar to BBC iPlayer?

Can HTML5 Videos automatically play on iPads? I used to believe that it wasn't possible because of iOS restrictions, but after trying BBC iPlayer on my iPad, I noticed that the videos did autoplay upon loading. Could this indicate that it is indeed ...

ASP.NET Core endpoint returning Http 405 MethodNotAllowed error

Vs.js code example - showcasing the axios.delete function and mounted sections: mounted() { this.getCreated(); }, deleteRequest(id) { axios.delete("http://localhost:32961/api/request/delete"+id) .then(() => { this.get ...

Guide on Showcasing Countries on a Global Map with Various Colors Using react-svg-map

I'm currently working on a project that involves highlighting specific countries on a world map. The default color for the countries is light blue, but I need to change it to dark blue for the highlighted ones. Although the library I'm using has ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...

Tips for choosing multiple files with the Ctrl key in a list item element:

We have decided to create our own browsing functionality due to the limitations of the existing HTML browse feature. While using the HTML browse, we can only select multiple files by pressing the Ctrl key, and we want to replicate this feature in our custo ...

The interval becomes congested due to the execution of two simultaneous Ajax calls

I have an Interval set to run a function every 3 seconds. intervalStepper = window.setInterval('intervalTick()','3000'); function intervalTick() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

What is the best way to integrate Vuex State data into methods?

Reviewing the code snippet below: <template> <div :id="svgId" class="svg-container"></div> </template> <script> import { mapState } from 'vuex' export default { name: 'Space', data: function() { ...

Allowing multiple requests to be executed simultaneously in Express.js without causing any blocking issues

I am facing an issue with my Express.js website while handling post requests. The server hangs when a request triggers a query that takes several minutes to execute and respond from the database. Below is the code structure I use for database queries: Se ...

Ways to activate an event with select2

Hey there! I have a unique setup on my selling item page with select tags. The first select tag is created using HTML, while the others are dynamically added using jQuery when the user clicks on an "Add More" button. <select id='code0' onclic ...

Learn the steps for submitting and interpreting information in Node Express

I am attempting to send this JSON data to a node express endpoint { "data": [ [ "Audit Territory", "LA Antelope Valley", "LA Central", "LA East San Gabriel", "LA San Fernando Valley", "LA West", ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

Avoid displaying identical items when rendering a page from JSON data

I am using ajax and json to render a page. The structure of my json is as follows: {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]}. I want to load the data using ajax only once if 'points' have duplicates in any of the ...

Using MVC to create dynamic JavaScript functions that call actions

Having trouble with dynamic JavaScript onchange event not firing in my application. Here's the code snippet from my action result: public ActionResult About() { ViewBag.Script = "<input type='text' name='myName&a ...

Vuejs Error: The 'in' operator cannot be used for searching

I am facing an issue with my form and VueJS. Upon clicking the "Login" button, I intend to change the text on the button. However, instead of achieving this, I encounter an error stating 'cannot use 'in''. Below is the HTML code snippet ...

Users are facing difficulties logging into my website due to mixed content issues in Laravel

As a beginner in Laravel + VueJS + Vuetify, I am reaching out for help with an issue I encountered. The web application I have was originally created by a remote developer and runs smoothly on my local machine. However, upon deployment to the staging site, ...

The combination of jQuery event handling and accessing undeclared event objects

While debugging someone else's code, I encountered a puzzling situation. The snippet of code provided below illustrates the problem. It seems to me that event should be undefined upon entering the event handler. This is indeed the case in Firefox, bu ...

Integrate the element offset into jQuery's offset calculations

I'm new to utilizing jQuery and currently facing a challenge in determining the correct offset for a specific div element within the body. My goal is to make this particular div stick to its position as I scroll down past its designated top offset. A ...