Choosing an option in Vue using select, v-for loop, and v-model

How can I set a preselected option in a select element using v-model, v-for for options, and an object as the value? The options are elements with unique ids, and I want to preselect based on custom equality (e.g., matching the id field). Is there a way to achieve this similar to AngularJS' track by feature in ng-options?

https://jsfiddle.net/79wsf1n4/5/

What's the best approach to preselect the input with the value that has an equal id?

Template:

<div id="vue-instance">
  <select v-model="selected">
    <option v-for="item in inventory" :value="item" :key="item.id">
      {{ item.name }}
    </option>
  </select>
  <p>
    {{ selected.id }}
  </p>
</div>

JavaScript:

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', id: 1},
      {name: 'MacBook Pro', id: 2},
      {name: 'Lenovo W530', id: 3},
      {name: 'Acer Aspire One', id: 4}
    ],
    selected: {
        id: 2
    }
  }
});

Answer №1

If you want to add the selected attribute, follow Dharmendra's suggestion.

The issue lies in assigning a valid object to the selected property. Vue will search for an identical object in your option list using object equality comparison.

Currently, it is uncertain if Vue can base the initial selection on an attribute. A simple workaround is to assign the selected property based on the ID in the created lifecycle callback:

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', id: 1},
      {name: 'MacBook Pro', id: 2},
      {name: 'Lenovo W530', id: 3},
      {name: 'Acer Aspire One', id: 4}
    ],
    selected: 2
  },
  created: function() {
        this.selected = this.inventory.find(i => i.id === this.selected);
  }
});

I have also made changes to your Fiddle.

Answer №2

You need to update how the value is assigned to the option. Replace :value="item" with v-bind:value="item".

HTML section

<select class="form-control" name="template" v-model="selected">
    <option v-for="item in inventory" v-bind:value="item">
       {{ item.name }}
    </option>
</select>

JavaScript section

new Vue({
  el: '#selector',
  data: {
    ...
    selected: {name: 'MacBook Pro', id: 2}
  }
})

Check out the demo on JSFiddle

Answer №3

There's a bunch of unnecessary code here, but it's useful for testing purposes (specifically, you need to set initSelect with either an id or a name):

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {name: 'MacBook Air', id: 1},
      {name: 'MacBook Pro', id: 2},
      {name: 'Lenovo W530', id: 3},
      {name: 'Acer Aspire One', id: 4}
    ],
    initSelect : {
    id: 2
    },
    selected: {},
  },
  created: function() {
    this.setSelectedWithInit();
  },
  methods: {
    setSelectedWithInit: function() {
      var firstKey = Object.keys(this.initSelect)[0],
        value = this.initSelect[firstKey];
      
      for( var i = 0, length = this.inventory.length; i < length; i++ ) {
      if( (this.inventory[i].hasOwnProperty(firstKey))
         && (this.inventory[i][firstKey] === value) )
        {
          this.selected = this.inventory[i];
          return;
        }
      }
    },
    toggle: function() {//you don't need this method
      if( this.initSelect.hasOwnProperty('id') ) {
        this.initSelect = { name: 'Lenovo W530' };
      } else {
        this.initSelect = { id: 2 };
      }
    }
  },
  watch: {
    'initSelect': {
      handler: function (val, oldVal) {
        this.setSelectedWithInit();
      },
      deep: true
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>

<div id="vue-instance">
  <select v-model="selected">
    <option v-for="item in inventory" :value="item" :key="item.id">
      {{ item.name }}
    </option>
  </select>
  <p>
    {{ initSelect.id }}
    {{ initSelect.name }}
  </p>
  
  <!-- You don't need the rest of the html below -->
  <button @click="toggle">Toggle id/name</button>
  
  <div v-if="initSelect.hasOwnProperty('id')">
    Id: <input v-model.number="initSelect.id" type="number">
  </div>
  
  <div v-else>
    Name: <input v-model="initSelect.name" type="text">
  </div>
  
  <br><br>
  {{ initSelect }}
</div>

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

What is the best way to remove top divs without causing the bottom divs to shift upwards?

I am faced with a scenario where I must remove the topmost divs in a document without altering the user's view. Essentially, I need to transition from: ---------start of document div1 div2 div3 ---------start of window div4 div5 ------- ...

What is the best way to bind data to a textarea component and keep it updated?

I started using VueJS just a week ago for a new project. During this time, I have successfully created two components: * Account.vue (Parent) <!--This snippet is just a small part of the code--> <e-textarea title="Additional Information" ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Having trouble with submitting the AJAX form when trying to rate something

Need help with the review rating code. The form submission does not save data to the database. Any assistance is appreciated. <form id="commentform" method="POST" action="#" class="form form-inline form-contact"> <p class="push-down-20"> ...

Panning is not compatible with shared camera OrbitControls

I am attempting to set up two renderers on separate div containers. Each renderer should have its own OrbitControls to update the camera associated with it. However, the camera is shared between the two renderers. The objective is to synchronize the camer ...

When trying to use selenium.WebDriver, an error pops up: "missing ) after argument list."

Trying to extract content from the ::after element is proving to be a challenge. Despite my attempts, I keep encountering an exception: "OpenQA.Selenium.WebDriverException: "javascript error: missing ) after argument list My setup includes VSC, Selenium ...

Challenges with sending JSON encoded Arrays from WordPress to PHP results in empty or NULL responses

My Plugins site has multiple Inputs that I need to gather values from and push them into an array. Then, I utilize the jQuery.post method to send this data to my PHP script. Javascript: var json = JSON.stringify(output); // output is an array with multip ...

Extracting the submit input value with jQuery while implementing AJAX on a form

Imagine you come across this code snippet: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title><!-- Put your title here --></title> <s ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...

Tips for ensuring that the dynamic view updates correctly when the scope variable is modified

I am currently working on an Angular SPA where a $scope variable plays a crucial role in determining the content of a specific page. When a user clicks on a different link in the menu, parameters are passed through the URL, updating the scope variable. How ...

"Exploring In-Depth Data Visualization: A Guide to Navigating Charts

It was shocking to me how scarce the information on this subject is. I have a ChartJS pie chart that I would like to delve deeper into by clicking on a slice of the pie. Do you have any suggestions on how to achieve this? ...

Preview Image Unavailable

I am currently working on a project that involves creating a form where users can upload an image and see a preview of it before submitting. Unfortunately, I am facing issues with getting the image preview to display correctly. Below is the HTML code snip ...

Is using JQuery recommended for implementing onclick and onchange events?

Hello there, I'm completely new to the world of jQuery and currently facing a bit of confusion. Here's my dilemma: should I be utilizing jQuery with the onclick event or the onchange event for an element using something like this: $(selector).som ...

What causes a Next.js App to crash when a prop is not defined in destructuring code?

Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType property that may not always be defined or may not exist at times. When I destructure it in this way: const { docType } ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

Having trouble sending a POST request to a Node.js HTTP Webserver unless it's from the localhost

I am currently facing an issue while attempting to transfer text/data from a client browser to a Node.js webserver. Whenever I try to use any IP address other than localhost, I encounter a "POST ERR_CONNECTION_TIMED_OUT" error. Below is the code snippet f ...

Establishing communication between a master process and worker processes in Node.js: A guide to verifying bidirectional communication

After coming across this particular script from the node documentation, I tried to implement it for sending messages between Master and worker processes using cluster. However, upon running the script, I encountered an issue where I could not verify the me ...

Load Materialize autocomplete with data from a JSON file

After hours of research, I am struggling to populate my autocomplete input using the Materialize plugin for a website project. Since I am not well-versed in json or ajax, implementing the original example from the documentation with static data has been qu ...

Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API. Index.js file: const express = require('express'); const http = require('http'); const morgan = require('morgan'); const b ...

I am seeking to incorporate several Three.js animations into my HTML document, but I am experiencing issues with them

As a professional graphic designer, I am facing an issue with Three.js https://i.sstatic.net/6ZsWa.jpg I have tried several solutions, but none seem to work effectively. In my attempt, I duplicated the imported model and changed its name. Despite trying ...