What is the best way to display the currently selected value in a Vue select drop down?

Is there a way to make the selected item in a custom component dropdown appear, similar to this Vue.js question? I have debug output within my single file component (SFC).

<script>
export default {
  props: ['modelValue', 'options'],
  emits: ['update:modelValue']
}
</script>

<template>
  <div>
    
  <select
    :value="modelValue"
    @change="$emit('update:modelValue', JSON.parse($event.target.value))"
  >
    <option value="" disabled>no selection</option>
    <option v-for="option in options" :value="JSON.stringify(option)" :selected="JSON.stringify(modelValue) === JSON.stringify(option)">X{{JSON.stringify(option)}}X{{JSON.stringify(modelValue) === JSON.stringify(option)}}</option>
  </select>
     {{modelValue}}
  </div>
</template>

Another component that calls this:

<script>
import CustomInput from './CustomInput.vue'

export default {
  components: { CustomInput },
  data() {
    return {
      message: '',
      blah: [
        {a:"a"},
        {b:2},
        {c:{d:1}},
      ]
    }
  },
  computed: {
        theMessage() {
      return JSON.stringify(this.message);
    }
}
}
</script>

<template>
  <CustomInput v-model="message" :options="blah"/> {{ theMessage }}
</template>

Even though the label appears to show the selected item, it doesn't get displayed as such in the dropdown. Can someone help me figure out why?

Playground

Answer №1

Utilize the v-model feature within your child component and propagate the event to the parent component using a computed setter/getter method

App.vue

<script>
import CustomInput from './CustomInput.vue'

export default {
  components: { CustomInput },
  data() {
    return {
      message: '',
      blah: [
        {a:"a"},
        {b:2},
        {c:{d:1}},
      ]
    }
  },
}
</script>

<template>
  <CustomInput v-model="message" :options="blah" /> {{ message }}
</template>

CustomInput.vue

<script>
export default {
  props: ['modelValue', 'options'],
  emits: ['update:modelValue'],
  computed: {
    internalValue: {
      get() {
        return this.modelValue;
      },
      set(newVal) {
        this.$emit('update:modelValue', newVal)
      }
    }
  }
}
</script>

<template>
  <div>
  <select
        v-model="internalValue"
  >
    <option value="" disabled>no selection</option>
    <option v-for="option in options" :value="JSON.stringify(option)" :selected="JSON.stringify(modelValue) === JSON.stringify(option)">{{
      option}}</option>
  </select>
  </div>
</template>

(The usage of JSON.stringify may not be necessary)

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

Using jQuery to load a text file and dynamically insert it into a specified div

How can I load a *.txt file and insert the content into a div? Here is my code: JavaScript: $(document).ready(function() { $("#load").click(function() { $.ajax({ url : "file.txt", success : function (data) { ...

Utilizing the power of AngularJS with ng-class for dynamic styling and

I recently started learning AngularJs and I have a question about how angular handles the ng-class attribute. While working with external libraries for visualization, charts, etc., I often need to trigger the resize event: window.dispatchEvent(new Event( ...

Chrome compatibility problem with scroll spy feature in Bootstrap 3

Having trouble with scroll spy for boosters using the body method " data-spy="scroll". It seems to be working for some browsers like Edge and Google Chrome, but after multiple attempts, it still doesn't work for me. Even after asking friends to test i ...

Vue alert: Issue encountered in watcher 'childItems' callback - 'TypeError: Unable to access property 'tag' as it is undefined'

I am currently in the process of developing the Store page for a web application. I am utilizing Axios to retrieve product data and display it in a Vue template. While the backend functionality is working correctly and the frontend is rendering successfull ...

Transform JSON into an Array and generate a new Array from a collection of Arrays

I'm struggling with generating a table in Angular2 from JSON data because I need to pivot the information, but my usual method doesn't seem to work for this scenario. Below is an excerpt of the JSON data I am working with: [ { "ValueDate" ...

jQuery menu fails to toggle the class name

The toggle functionality in the Menu is not working properly. Upon clicking the toggle button, I encountered the following JavaScript error: "message": "Uncaught TypeError: Cannot read property 'toggle' of undefined", "filename": "https://st ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Set markers at specific locations like "breadcrumbs" and generate a route using Google Maps API v3.exp

I'm developing a new iOS application for scouting out locations while on the move. I want users to be able to mark each location by simply clicking a button, which will drop a marker based on their current location. The ultimate goal is to connect all ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Issue with Mobile Touch Screen Preventing Vertical Scrolling

Currently experiencing difficulties with a div element that is not allowing touch and vertical scroll on mobile devices. Although scrolling works fine with the mouse wheel or arrow keys, it does not respond to touch. Have tested this on various devices and ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: https://i.sstatic.net/GpvfC.png <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={th ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

Display all event date markers, even if some dates are missing

Using the FullCalendar plugin has been a great experience for me. I have managed to successfully read data from a JSON object with the following code: function press1() { var employees = { events: [] }; ...

Vue-ctl project creation halted by operating system rejection

While working on a Vue-CLI project, I encountered an issue. Has anyone else faced this problem before? Operating system: Windows 10 - Command Prompt (admin rights) @vue-cli version: 4.5.4 npm version: 6.14.6 Here is the command I ran: vue create font_ ...

An Iframe lacks the ability to showcase HTML content, unlike a browser which is capable of doing

I'm struggling to get my Iframe to show the html string properly. Here's the content of the string: var='<BODY style="MARGIN: 0px" bgColor=#ffffff marginwidth="0" marginheight="0"> <SCRIPT language=JavaScript> var Caller_User_Ty ...