Guide to displaying options in the Vue material select box even when the default value is blank

I have implemented the material design framework vuematerial with vue.js.

In traditional HTML, a selection box looks like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

When you run the script, the selection box should initially display "You should initially see this"

However, when using vuematerial to achieve a similar result:

<template>
  <div>
    <div class="md-layout md-gutter">
      <div class="md-layout-item">
        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'BasicSelect',
    data() {
      return {
        movie: '',
      }
    }
  }
</script>

Demo link

Instead of seeing an empty select box, I expect to see one with "Default film" selected. Changing the value of the first option to something other than an empty string fixes this issue, but that workaround does not work for my current scenario where the default value needs to be an empty string. Is there a way to show the initial value?

Answer №1

To determine the final selected result, you can utilize a computed property. Start by setting your initial option value and variable movie to a string, like "default". Then create a computed property to return the ultimate result as shown in the code snippet below:

Vue.use(VueMaterial.default)
new Vue({
  el: '#app',
  data: {
    movie: 'default'
  },
  computed: {
    selectedMovie() {
      return this.movie === 'default' ? '' : this.movie
    }
  }
})
#app {
  padding: 30px;
  margin: 50px 0;
}

#selected {
  padding: 15px;
  background: skyblue;
  color: black;
  margin-top: 30px;
}

.as-console-wrapper {
   height: 0;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bfbcac89fbe7ffe7f8f9">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e6e5f5bdfdf1e4f5e2f9f1fcd0a1bea0bea0bdf2f5e4f1bda1a1">[email protected]</a>/dist/vue-material.min.js"></script>
<link href="https://unpkg.com/vue-material/dist/theme/default.css" rel="stylesheet"/>
<link href="https://unpkg.com/vue-material/dist/vue-material.min.css" rel="stylesheet"/>

<div id="app">
  <div class="md-layout md-gutter">
    <div class="md-layout-item">
      <md-field>
        <md-select v-model="movie" name="movie" id="movie">
          <md-option value="default">Default film</md-option>
          <md-option value="fight-club">Fight Club</md-option>
          <md-option value="godfather">Godfather</md-option>
          <md-option value="godfather-ii">Godfather II</md-option>
          <md-option value="godfather-iii">Godfather III</md-option>
          <md-option value="godfellas">Godfellas</md-option>
          <md-option value="pulp-fiction">Pulp Fiction</md-option>
          <md-option value="scarface">Scarface</md-option>
        </md-select>
      </md-field>
    </div>
  </div>
  <div id="selected">Selected Movie: {{selectedMovie}}</div>
</div>

Answer №2

The functionality differs with vue-mdc. Referencing the documentation at , it specifies that you must define the label prop of md-select in order to show a default value.

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

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

The code snippets in the Vue3 documentation are quite peculiar

As I peruse the Vue 3 documentation, I notice a recurring pattern in how example code is presented for components: Vue.createApp({}) However, my experience with Vue 3 has been different. Instead of the above syntax, I simply use: <script> export d ...

What is the best way to show a message within a specific HTML division with JavaScript?

Here's my attempt at solving the issue: <head> <script> function validateForm() { var username = document.forms["login"]["uname"].value; var password = document.forms["login"]["pwd"].value; if (username == "" || p ...

What is the easiest way to modify the color of a basic PNG image in a web browser?

While working on a website project, I encountered instructions for mouseover styles in the design that got me thinking: It's straightforward to achieve with javascript or css image swapping... but here's the catch. There will be multiple icon li ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

What strategies can I use to keep an element in place while implementing parallax scrolling?

Looking for some assistance with my Codepen project. I am attempting to replicate a layout similar to this BBC article design from the past, but hitting a roadblock with getting my image to be position fixed based on scrolling. I believe that if I can suc ...

What is the best way to showcase the information of each object on a click event in Vue.js?

My goal with this code is to display each day's class schedule when it is clicked on. However, the issue I'm facing is that the entire week's schedule is being displayed instead of just the selected day. What adjustments should I make in ord ...

Why does the appearance of my PHP spreadsheet change when I attempt to print it?

After using a CSS stylesheet to position my textboxes correctly, I noticed that in Chrome everything appeared fine. However, when attempting to print the site (Ctrl+P), each sentence and textbox shifted. How can I ensure they remain in place? <!-- #cap ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

How can you troubleshoot code in NextJS API routes similar to using console.log?

Incorporating nextjs API routes into my upcoming project has been a priority, and I recently encountered an issue with code execution upon sending a POST request. Debugging has proven to be challenging since I am unable to use conventional methods like co ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Different tiers of log levels

I am trying to figure out how to log only "INFO" level messages to the console for users, and to a file store "DEBUG" level posts. Currently, I have come across a solution that involves using multiple "getLogger()" functions like so: log4js.getLogger(&ap ...

MailJet experienced a template language issue while trying to send a message with Template [ID]

While running a test on a MailJet email template that includes a basic custom HTML code block, an error occurs in the received test email. (The live preview in the browser functions correctly) From [email protected]: An issue with the template lang ...

The AJAX response is not functioning as expected

I've encountered an issue with my AJAX code for an online food store. Every time I run it, a pop-up message saying something went wrong appears instead of the expected output. I suspect there might be an error in either the connection handlers or the ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

The Intersection Observer API is not compatible with using transform: translateX()

After successfully implementing the Intersection Observer API on my website and incorporating a few transitions from an example I came across, everything seemed to be working smoothly. You can view the scale-in transition in action here: https://jsfiddle.n ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 ...

"Exploring the best way to loop through multiple JSON data in a jQuery response

https://i.stack.imgur.com/O0F6g.pngMy JSON response contains multiple data points presented as follows. WellNames […] 0 {…} id 56 well_name AL HALL api 34005205550000 1 {…} id 498 well_name BONTRAGER api 34005233850000 2 {…} id 499 ...