In a JavaScript array of objects, the Vuetify select :items feature allows you to assign an id and name to each object. When a name is selected, the corresponding id is automatically

I am currently working with an array of objects that contain both an id and a name property:

Teams [
    { id: 1, name: 'team1' },
    { id:2, name: 'team2' } 
]

Is there a way to dynamically pass the names as items in a vuetify select component, where selecting a name would automatically set the corresponding object's id as the v-model value?:

<v-select
  v-model="???"
  :items="???"
  label="Teams"
></v-select>

I assume this functionality needs to be implemented within the created method, but I'm unsure about the correct approach. Currently, I populate the teams array with data fetched from the app's initial store retrieval:

this.teams = this.$store.state.teams.teams

The data is retrieved from a Laravel backend as a collection, leading me to consider transforming it into an id: name key-value pair on that end, even though it feels unnecessary. At present, my resource controller utilizes the following eloquent query in the index method:

$teams = Team::all();

return response()->json($teams);

I have experience implementing this feature using a standard select element, but I am uncertain about how to proceed with Vuetify’s v-select component:

<select id="categories" v-model="selectedValue">
    <option v-for="item in items" :value="item.id">{{ item.name }}</option>
</select>

Answer №1

Here is the recommended way to do it:

<html>

<head>
  <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>

<body>
  <div id="app">
    <v-app>
      <v-select v-model="data" :items="items" label=" Teams " item-text="name"
   item-value="id"></v-select>

      <div>
        {{data}}
      </div>
    </v-app>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
  <script>
    vue = new Vue({
      el: '#app',
      data: () => ({
        data: "",
        items: [{
            id: 1,
            name: 'one'
          },
          {
            id: 2,
            name: 'two'
          }
        ]
      })


    });
  </script>
</body>

</html>

Answer №2

To achieve this, you just need to modify your declaration like so:

<v-select
  :items="array-of-objects"
  label="Teams"
  item-text="id"
  item-value="name"
></v-select>

According to the documentation:

You can provide an array of objects or an array of strings. When using objects, the component will search for a text and value field within each object. You have the option to change these fields by using the item-text and item-value props.

Reference: https://vuetifyjs.com/en/components/selects

In essence, you can pass an array of objects to :items, but they must contain both a text and a value property. By utilizing the directives item-text and item-value, you can tailor them to suit your specific needs.

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

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

Implementing an ajax search functionality

I am currently working on implementing an AJAX search feature into my project. The application initially displays all client data in a table on the webpage. When something is typed into the search bar, I want the search results to be shown instead of all ...

utilizing axios encoding settings within vue.js

I am currently utilizing vue.js along with axios to retrieve data from an API endpoint. The specific URL I require is structured like this: https://base_url.com?f=json&where=&returnGeometry=false&spatialRel=esriSpatialRelIntersects&geometr ...

The PhantomJs browser is not able to open my application URL

Recently, my scripts in PhantomJS browser have stopped running. Whenever I try to capture screens, all I get are black screens. To troubleshoot this, I manually opened a URL in PhantomJS using the command window and ran the script below to verify if it ope ...

Enhanced JavaScript Autocompletion in Integrated Development Environments

What is the inner workings of Intellisense in IDEs like Webstorm and Eclipse for JavaScript? From which source do the suggestions originate? Is it possible to tweak the code to enhance the accuracy of the suggestions? https://i.sstatic.net/ZVBB3.png ...

Ending the jQuery Modal box

Struggling to create a simple modal on my own, and I'm facing some difficulties (probably because I'm more of an expert in jQuery - but let's not dwell on that too much). This is the HTML markup I have: <div id="modal-boxes"> < ...

The actions creator is triggered twice when using componentWillMount to dispatch actions

When I call the action creator using componentWillMount method, it seems to get called twice. You can see the screenshot below for the result. https://i.sstatic.net/1Xi1D.png This is the action creator I am using: export function fetchAdmin(){ retur ...

Node.js with Koa: Discontinuation of generator usage on the next step

I am working with a custom object in which I pass a parameter, and then I need to search for all documents in my collection and process them. Here is the code for my custom object: var db = require('../lib/db'); function Widget(n,l,c,o,t,p) { ...

A step-by-step guide on extracting the image source from a targeted element

Here is a snippet of my HTML code containing multiple items: <ul class="catalog"> <li class="catalog_item catalog_item--default-view"> <div class="catalog_item_image"> <img src="/img/01.png" alt="model01" class="catalog_it ...

One way to display the contents of a div after the CSS has finished loading

Here is the code snippet that I am currently working with: $.ajax({ type: 'GET', url: 'url.php', success: function(data){ $("div#mainclass").hide().html(data).fadeIn(100); } }); After implementing this code, I ...

Having issues with Oruga UI functionality on Vue 3. None of the elements are responding as intended. Is there a specific step I may be missing to utilize them

Every time I incorporate an oruga UI component into my vue app, even the simplest ones, it triggers errors. For instance, consider the code snippet below: <template> <o-field label="Name"> <o-input v-model="name" / ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Incorporating Layouts and Partials in Handlebars Template

Can you provide guidance on incorporating layouts and partials with handlebars templates like the example below? I have reviewed the documentation on partials but am still struggling to achieve my desired outcome. default.html The default layout is util ...

Is it possible for jQuery to execute in a sequential manner?

Below is the code I am working with: https://jsfiddle.net/c4zquo60/1/ CSS: #bg { background-repeat: no-repeat; position: absolute; top:0; bottom:0; left:0; right:0; width:100wh; height:100vh; z-index: -1; opacity: ...

Quasar Vue problem: Address autocomplete in Google without using a map

I've been working with the Quasar framework and utilizing the VueGmaps package for address autocomplete. I installed the package using npm install vue-gmaps --save <script> import Vue from "vue"; import VueGmaps from 'vue-gmap ...

Request to convert jQuery Ajax code into Vanilla JavaScript code

Are there any vanilla JavaScript alternatives available for the code snippet below? function verifyEmail() { var apiUrl = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email&apos ...

Enhancing JavaScript Objects with New Key/Value Pairs

I'm trying to wrap my head around the code structure of a solution I stumbled upon. The issue at hand: Create a function that takes in a string with only lowercase letters as a parameter, and returns an object with each letter and the number of times ...

In what way can an array be assigned to a new key within the same key along with additional objects?

My goal is to transform the existing key value into a new format within the same key. It may be difficult for me to explain clearly through words, but the following data will help clarify. The data is currently structured as follows: const sampelData = [{ ...

Obtained a ZIP file via CodeSandbox that contains a Vue.JS webpage. However, the index.html file yielded an

I have created my first ever Vue.JS / Vue2Leaflet app. It runs perfectly fine on codesandbox.io. However, when I download the ZIP file and try to open the index.html file, it appears blank. Is there something specific that needs to be done to make it work, ...