Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one?

For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are another. When an option is selected in select 1, it should not affect select 2, and vice versa.

I'm thinking maybe a computed property could help achieve this, but I'm struggling to figure out the correct implementation.

You can view the Js fiddle example here.

Here's a code snippet:

new Vue({
  el: '#app',
  template: `
        <div>
            Select 1: <select v-model="selectedPerson">
                <option v-for="person in people" :value="person.key">{{person.name}}</option>
            </select>
            Select 2: <select v-model="selectedPerson">
                <option v-for="person in people" :value="person.key">{{person.name}}</option>
            </select>
            <h4>Selected 1 person key : {{selectedPerson}}</h4>
             <h4>Selected 2 person key: {{selectedPerson}}</h4>
            
            <br/>
                       Select 3: <select v-model="selectedPersonTwo">
                <option v-for="person in people" :value="person.key">{{person.name}}</option>
            </select>
            Select 4: <select v-model="selectedPersonTwo">
                <option v-for="person in people" :value="person.key">{{person.name}}</option>
            </select>
            <h4>Selected 3 person Two key: {{selectedPersonTwo}}</h4>
            <h4>Selected 4 person Two key: {{selectedPersonTwo}}</h4>
        </div>
    `,
  data: {
    people: [{
        key: 1,
        name: "Carl"
      },
      {
        key: 2,
        name: "Carol"
      },
      {
        key: 3,
        name: "Clara"
      },
      {
        key: 4,
        name: "John"
      },
      {
        key: 5,
        name: "Jacob"
      },
      {
        key: 6,
        name: "Mark"
      },
      {
        key: 7,
        name: "Steve"
      }
    ],
    selectedPerson: "",
    selectedPersonTwo: ""
  }
});
.required-field > label::after {
  content: '*';
  color: red;
  margin-left: 0.25rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<body>
  <div id="app"></div>
</body>

Answer №1

It seems like you are interested in implementing two-way binding with more personalized control. Here's a suggestion:

  • Avoid using
    <select v-model="selectedPerson">
  • Instead, break it down into
    <select :value="selectedPersonValue" @input="selectedPersonOutput">
    (essentially achieving the same result, but allowing for distinct inputs and outputs). Define selectedPersonValue as a computed or regular property within data(), and make selectedPersonOutput a method that triggers when the select value changes.

This approach grants you direct control over each stage of the process.

Note: If you wish to manipulate the selectedPersonValue property from a method, consider moving it to a data property and setting up a watch on it. Experiment to determine the most effective solution for your 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

challenges encountered when saving a getjson request as a variable

I am experiencing difficulties in retrieving a variable from a getJSON() request. The issue lies within the following three functions: function getPcLatitude() { // onchange var funcid = "get_postcode_latitude"; var postcode = parseInt($('#i ...

Is there a way to use Javascript to determine if a string within a JSON object has been altered?

I am looking for a way to continuously monitor changes in a specific string or date stored in a JSON file. How can I effectively store this value and create a mechanism to compare it for any differences? Any assistance would be highly appreciated. // Ex ...

Using Vuejs v-for to dynamically display unique data

Clicking on the button allows me to add a component. <button type="submit" @click="components++">add select box</button> <div v-for="component in components"> <select class="selectpicker form-control" v-model="customized_exercise. ...

What is the specific function of $('id').on('click', this.method.bind(this)) in this scenario?

Check out the app I'm talking about here: I am delving into the bind method in JavaScript to grasp its essence. Upon experimenting with it in the console, my interpretation is that bind produces a duplicate of the function, wherein "this" is tethere ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Saving similar and dissimilar information in a database

I have been working on implementing a Like and Unlike feature for users to interact with products. Following this tutorial at , I've completed the necessary steps. However, I'm facing an issue where the likes are not being stored in the database ...

Is it possible to nest axios post requests within another axios post request?

Can someone assist me with getting the session ID from the API to utilize it as a part of my input for an Axios POST request in order to retrieve user information? Despite double-checking my code thoroughly, I keep encountering a session expired error. Any ...

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

A simple way to retrieve the computed value from one ng-model and assign it to a different ng

I am facing an issue where I have 3 ng-models and I need to fetch calculated data from the first two into the third one using angularjs I attempted a solution but it doesn't seem to work as expected Below is the HTML code snippet: var urlt = ' ...

Using Jquery UI dialog to ensure validation

function DisplayDialog() { $("#dialogid").dialog({ width: 300, modal: true, show: 'drop', hide: 'drop', buttons: { "Ok": function () { return true; $(this).dialog('close'); }, "Cancel": func ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

Should Redux Reducer deep compare values or should it be done in the Component's ShouldComponentUpdate function?

Within my React Redux application, I have implemented a setInterval() function that continuously calls an action creator this.props.getLatestNews(), which in turn queries a REST API endpoint. Upon receiving the API response (an array of objects), the actio ...

When I tried to retrieve the value by using deferred.resolve(value) in my .then() method, it

I am currently utilizing Q.js to make an API call with two loops in my main function structured like this: for i..10 for i...5 var promise = getLoc(x,y); promise.then(function(value) { //value is undefined... ...

The HTML Canvas seems to be malfunctioning for some unknown reason

As a beginner in programming, I am struggling to understand why the code below is not working. The first three lines of the script are necessary for another part of the webpage, but I don't see how that would affect the rest of the code: <!DOCTY ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

When using Browsersync in a single page application, an "Refused to execute inline script" error may occur if the route is not at the root level

I encountered the following error while using my Vue SPA: Refused to execute inline script due to Content Security Policy violation with directive "default-src 'self'". To allow inline execution, use 'unsafe-inline', a hash ('sha2 ...

What is the best way to display text based on the current URL?

Using vue-router, I am attempting to maintain a title that specifies the section. For instance: In the main navigation, I want to display the text of the current section (not the active class, just plain text with the section). Here is the pattern of URL ...

Having difficulty generating a footer for a page that includes a Material-UI Drawer component

Looking to create a standard full-width footer at the bottom of my page, I need help with the implementation. Utilizing the "Permanent drawer" from Material-UI Drawer for reference here. If you're interested in experimenting with it, CodeSandbox link ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...