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

Learn the easy steps to position an image to the right using FreeMarker

I'm attempting to align the final image on the right side of the page in order to achieve a symmetrical look. The code I have been using in FTL is as follows, but it consistently ends up next to the middle section: <table class="h ...

Encountering a syntax error with the AngularJS ng-class expression

While navigating through a tutorial application designed for use with the Ionic platform, which is based on angular 1.2.4, I encountered a perplexing error in this Angular markup: <content has-header="true" scroll="false"> <list> ...

When using selenium with python, the function excecute_script('return variable') may not technically return variables, even though the variable does exist

My attempt to retrieve a variable from javascript code using selenium is encountering difficulties. Despite the presence of the variable (confirmed by inspecting the source code before executing the script), the command driver.execute_script('return v ...

Error in Angular Universal: KeyboardEvent is not defined

I have inserted the word "domino" into the server.ts file and updated the webpack.server.config.js as follows: module: { rules: [ { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '&bs ...

Unable to submit form within a while loop in PHP table

After making some changes to my form, I noticed that only the hidden input field is being submitted when I try to submit the form. It's strange because it was working perfectly fine before. while ($row = mysqli_fetch_array($gettimesheets)) { $dat ...

What is the best way to set a default option using V-bind when working with an object?

Recently, I've been working on some vue.js code that looks like this: <template> ... <div v-for="guest in guests" :key="guest"> <label for="attendance">Will {{guest}} be attending? </label> ...

Issue with injecting Angular service in unit test

Hello, I'm currently working on a simple test: define(["angular", "angularMocks", "app", "normalizer"], function(angular, mocks, app) { describe("service: normalizer", function () { var normalizerService; beforeEach(module("ADB")); b ...

The justify-position attribute does not have any impact on the positions that are set

Here is the JSX code that resembles HTML but uses ClassName instead of class: <div className="snavbarcontainer"> <div className="toplefticon"> <a class="test" href=" ...

Avoid making GET requests when clicking on a link

[UPDATE] I need help troubleshooting an issue with my ajax request. Here is the code snippet that I am working on: <a href="" class="undo_feedback">Undo</a> When I click on the link, it triggers an ajax POST request, but I encounter an error ...

Issue with initializing Nuxt in GitHub Actions resulting in a critical error

I'm currently stuck on a Nuxt Fatal error while running a GitHub actions workflow for a nuxt app with cypress.js testing. Despite trying to decipher the stack trace, I can't seem to pinpoint the root cause of this issue during the app build. For ...

Exploring the possibilities of NodeJs by analyzing an HTML form

I'm facing an issue while evaluating an HTML Form using NodeJs and Express. Here's my JavaScript Code My aim is to manage HTML Forms in NodeJs using Express. const express = require('express'); const http = require('http'); ...

"Encountering a 403 error while using the request method in Node.js

app.post("/",function(req,res){ // console.log(req.body.crypto); request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){ console.error('error:', error ...

I am having trouble with the prime number finder in my JavaScript program. It seems to not work for certain values. What could be

I am in the process of developing a code to identify prime numbers less than n. However, I encountered an issue where the code mistakenly flags 33 and 35 as prime numbers. I am puzzled by this unexpected outcome. Here is the code that I have been working o ...

Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after ...

Issue with Bootstrap modal not closing automatically after submitting an ajax form

I am facing an issue with a modal on my page that is used for submitting courses registered by students. Even after successful submission, the modal closes but leaves behind a faded background. I have attempted various solutions from StackOverflow without ...

implementing a SetTimeOut function following the clicking of a button

Hey there, I've been working on a code snippet that switches the display state from block to none with an onClick function. However, I'm looking to add a delay before the state change happens so that there's time for an animation effect to ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Tips for locating a webpage element with Selenium?

click here for image driver=webdriver.Chrome() driver.get("https://compass.tinkoff.ru/") driver.maximize_window() driver.implicitly_wait(20) elem = driver.find_element(By.XPATH, '//button[text()="Open Full Map"]').click() tim ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

Updating the value of a v-text-field in Vuetify

What is the best way to modify input values? Here is an example: `https://jsfiddle.net/mbqjp4ax/` If a number entered is greater than 5, the system should automatically input the number 9 instead. While this works correctly when entering numbers greater ...