Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation.

The issue at hand is encountering an error message for the custom select component:

[Vue warn]: Avoid directly mutating a prop as its value will be overwritten during parent component re-renders. Instead, utilize a data or computed property based on the prop's value. The prop being mutated: "value"

found within

--->

However, converting value into a data property leads to loss of expected functionality where the select box does not update upon value changes, causing a loss of two-way binding.

What is the proper approach to maintain the intended behavior without triggering warnings?

See below for an interactive demonstration showcasing the problem (best viewed in full screen).

Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
  methods: {
    changed() {
      // Custom input components should emit the input event
      this.$emit('input', event.target.value)
    },
  },
})

Vue.component('dynamic-select-ex2', {
  template: '#dynamic-select-template',
  props: ['options'],
  data() {
    return {
      value: null,
    }
  },
  methods: {
    changed() {
      // Custom input components should emit the input event
      this.$emit('input', event.target.value)
    },
  },
})

let example = new Vue({
  el: '#example',
  data() {
    return {
      selected: null,
      options: [
        { text: 'Hello', value: 1 },
        { text: 'World', value: 2 },
        { text: 'Blah', value: 3 },
        { text: 'Blerg', value: 4 },
      ]
    }
  },
  computed: {
   text() {
     if (!this.selected) return
     return this.options.find(({ value }) => value == this.selected).text
   },
  },
  methods: {
    select(value) {
      this.selected = value
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="dynamic-select-template">
  <select v-model="value" @change="changed">
    <option v-for="option in options" :value="option.value">{{ option.text }}</option>
  </select>
</script>

<div id="example">
  <label for="direct">Vue behaviour for native select</label><br>
  <select id="direct" v-model="selected">
    <option v-for="option in options" :value="option.value">{{ option.text }}</option>
  </select><br>

  <div>Vue behaviour for custom component. `value` is a prop. Warning output in console when user selects option</div>
  <dynamic-select-ex1 v-model="selected" :options="options"></dynamic-select-ex1><br>

  <div>Vue behaviour for custom component. `value` is a data property. Two-way binding is broken. Selected option not updated when `value` changes.</div>
  <dynamic-select-ex2 v-model="selected" :options="options"></dynamic-select-ex2><br>
  
  <br>Selected: {{ text }}<br><br>
  
  <button @click="select(1)">Hello</button>
  <button @click="select(2)">World</button>
  <button @click="select(3)">Blah</button>
  <button @click="select(4)">Blerg</button><br>

</div>

Answer №1

Smart Way to Handle Data Updates

Instead of directly manipulating the prop using v-model, it is recommended to utilize a computed setter. This helps in preventing any unwanted changes to the prop value and eliminates the need for a separate change listener.

<select v-model="model">
  <option v-for="option in options" :value="option.value"gt;{{ option.text }}</option>
</select>
Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
  computed: {
    model: {
      get() { return this.value },
      set(value) { this.$emit('input', value) }
    }
  }
})

This approach ensures that accessing the computed value returns the prop value, while setting it emits the new value instead.

Alternative Approach using One-Way Binding

Another method is to establish a one-way binding between value and $emit directly from the template:

<select :value="value" @input="$emit('input', $event.target.value)">
  <option v-for="option in options" :value="option.value">{{ option.text }}</option>
</select>
Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
})

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

Is it possible to safeguard undisclosed data in browser console?

Can JavaScript be employed to prevent users from editing hidden fields through the browser console? ...

How can I effectively send data from a view to a controller using AJAX in C# using Leaflet?

Every time I attempt to pass data from the view to the controller, I keep receiving an "alert request failed" message. I am uncertain of the datatype for leafletLats and leafletLngs, but they are both arrays derived from coord which is of type LatLng[]. ...

Utilizing Facebook's JavaScript SDK to transmit variables to PHP using ajax

Thank you in advance for your attention. I am trying to utilize the Facebook js SDK to retrieve the user's name and id, and then send them to PHP on the same page (index.php). After successfully obtaining the username and id and storing them in two Ja ...

improve your AJAX implementation in Django

Recently, I implemented some AJAX functionality in a Django application that I have been developing. Coming from a background in Ruby on Rails, I haven't had much experience with pure JavaScript. So, inspired by Rails' partials, I came up with ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Unleash the Power of Your Webpage: Instantly Engage Full

Is there a way to automatically make a webpage open in full screen mode as soon as it is loaded? Here's what I currently have: var elem = document.documentElement; function openFullscreen() { if (elem.requestFullscreen) { elem.requestFull ...

The power of Karma, AngularJS, Bootstrap, and the window variable working

As I work on testing my application, I am facing an issue with loading files using Karma into PhantomJS. The problem arises when one of the files triggers a page reload due to window variables. The files are being included in this manner: files: [ &a ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Encountering issues with Visual Studio Code following the integration of the MongoDB API Mongoose into my code

As I delve into the world of web development, I have been exploring databases with MongoDB Atlas and mongoose. Interestingly, my debugging process has hit a bump when using the node.js(legacy) debugger in VS code after importing mongoose with const mongoos ...

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

Tips on using Jquery to animate an element to a specific pixel measurement

My expertise lies in executing the following code: $("#nurseView").animate({"left": "+=100px"}, "slow"); However, I am facing a dilemma. How can I animate an object to exactly 1576px on the X-axis regardless of its current position? The code snippet abov ...

Unable to dynamically change the value of the submit button using angular.js

I'm facing an issue with setting the submit button value dynamically using Angular.js. The code I've written below explains my problem. <body ng-controller="MainCtrl"> <input type="submit" value="{{ !model ? 'reset' : mod ...

Is there a simple method to add animation to a group of images displayed on click using JQuery?

Here is my JavaScript code that I'm currently using: $(document).ready(function() { $(".button-list .next").click(function() { project = $(this).parents().filter(".projektweb").eq(0); currentimg = project.find(".im ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

A comprehensive guide to leveraging synchronous execution of setTimeout in JavaScript

Can the desired output shown below be obtained using setTimout? If it is possible, please provide your insight: console.log("1st"); setTimeout(() => { console.log("2nd"); },0); console.log("3rd"); The expected output should be: 1st 2nd 3rd ...

Transferring information and storing it in a textbox

I have a homepage that features a popup window. <textarea class="form-control item"></textarea> <button type="button" class="btn btn-primary" name="name">Send</button> Additionally, there is a secondary page at (/conclusion/main) ...

What are the effects of calling callback(false) and callback(true)?

I'm currently diving into a nodejs chat project, and I’m a bit confused about the outcome when callback(false) and callback(true) are triggered in this context... io.sockets.on('connection', function(socket){ socket.on('new user& ...

My global variable keeps getting caught by the addEventListener function

My script does not use jQuery and has an addEventListener on a button click. The issue is that after the first run, I want to change the value of "sendingurl" to something else. However, even though sendingurl is updated with the new id value, it doesn&apo ...

Why does my anchor disappear after a second when clicked to show the image?

Hi everyone, I'm having an issue with a dropdown menu that I created using ul and anchor tags. When I click on one of the options, an image is supposed to appear. However, the problem is that the image shows up for just a second and then disappears. I ...

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...