Choose the default selection for the first item in a populated select using v-model in Vue JS

I am facing a tricky challenge in Vue.js - I need to create two select fields. The first one should be used to select between fruits and vegetables, and based on that selection, the second field should dynamically display the corresponding list of items.

I have searched online for similar solutions, but I am struggling with how to set the default selected item in the second select field when switching between fruits and vegetables.

My goal is to have the first item in the second select field automatically selected whenever I switch between fruits and vegetables in the first select field.

Please take a look at my code here: https://jsfiddle.net/aj6g87dh/1/

new Vue({
  el: '#test',
  data: {
    category: 'fruits',
    list: '',
    optionsData: {
       fruits: [
            { text: 'Orange', value: 'orange' },
            { text: 'Banane', value: 'banana' },
       ],
       
       vegetables: [
           { text: 'Brocolis', value: 'brocolis' },
           { text: 'Radish', value: 'radish' },
       ]
    }
  },

  computed: {
    options: function() {
      let options = ''

      switch (this.category) {
        case 'fruits':
          options = this.optionsData.fruits
          break;

        case 'vegetables':
          options = this.optionsData.vegetables
          break;

        default:
          options = this.optionsData.fruits
      }

      return options
    }
  },

  methods: {
    onChange: function() {
      this.options = this.options
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.js"></script>
<div id="test">
  <select v-model="category" v-on:change="onChange" id="select1">
    <option value="fruits">Fruits</option>
    <option value="vegetables">Vegetables</option>

  </select>

  <select id="select2" v-model="list">
    <option v-for="option in options" v-bind:value="option.value"> {{ option.text }} </option>
  </select>

  <span>{{  }}</span>

</div>

Answer №1

To enhance the functionality, consider replacing the onChange method with a watch property for better handling of change logic.

Additionally, streamline the options retrieval process by condensing it to a single line.

new Vue({
  el: '#test',
  data: {
    category: 'fruits',
    list: '',
    optionsData: {
      fruits: [{
          text: 'Orange',
          value: 'orange'
        },
        {
          text: 'Banane',
          value: 'banana'
        },
      ],

      vegetables: [{
          text: 'Brocolis',
          value: 'brocolis'
        },
        {
          text: 'Radish',
          value: 'radish'
        },
      ]
    }
  },

  computed: {
    options: function() {
      return this.optionsData[this.category]
    }
  },
  watch: {
    category: {
      handler: function(newVal) {
        this.list = this.optionsData[newVal][0].value;
      },
      immediate: true
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="test">

  <select v-model="category" id="select1">
    <option value="fruits">Fruits</option>
    <option value="vegetables">Vegetables</option>

  </select>

  <select id="select2" v-model="list">
    <option v-for="(option, i) in options" v-bind:value="option.value"> {{ option.text }} </option>
  </select>

  <span>{{ }}</span>

</div>

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

Steps for rapidly expanding a Keno UI window while simultaneously changing icons

I've been struggling to understand why my attempts at implementing a custom expand button on Kendo are not working as expected. The goal is to have a button that expands the window to 75% and then contracts it back to 34%. VIEW @(Html.Kendo().Window ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

The property 'titulo' of 'actividad' cannot be destructured because it is currently undefined

I'm currently utilizing the useParams hook to fetch a custom component. It successfully renders the id, but nothing more. Here's a snippet of my code: import React, { useState } from "react"; import { Link } from "react-router-dom ...

Quasar Framework Vue.js project experiencing unexpected disablement of console/debug output in PWA InjectManifest workbox

I recently added PWA capability to my project built with Vue.js / Quasar Framework. After changing the "workboxPluginMode" property to "InjectManifest", I noticed that Workbox was initially giving me debug information in the console as expected. Moreover, ...

Is there a specific advantage to iterating through arrays backwards in JavaScript?

Is it common practice in Javascript to use the following loop: for (var i = array.Length - 1; i >= 0; i--) { /* do something here */ }; I haven't seen this in other languages. Are there any advantages to this compared to: for (var i = 0; i < ...

Validate the historical and present contents of a variable

Let's take a look at my code snippet: <button id="submit">Roll</button> <script> function generateRandomNumber(range) { var result = ''; var characters = '123456789'; var c ...

Navigate directly to a specific slide in jQuery Cycle without using a pager manually

Is there a way to programmatically advance to a specific slide in jQuery cycle instead of relying on pager clicks? Similar to how you can advance using this syntax: $('#slideshow').cycle('next'); I am interested in passing a specific ...

Consolidate nested object in D3

After removing duplicate rows from my dataset using a d3.nest() function, I now have unique entries in my JSON array. My goal is to calculate the mean 'cycle time' for each date. The desired output should resemble: [ { "key": "2012-03", ...

What could be hindering my jQuery function from running the Ajax script?

My jQuery function is supposed to retrieve two values, one for school/college and one for state, and send it to the controller class under the URL "Type&State". However, for some reason, the data is not being passed and nothing is shown in the console ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

Guide on changing the font size of a selected tab in material-ui

My requirement specifies that the active tab should be styled with a specific color and font size only. Here is my code snippet: <Tabs value={value} onChange={handleChange} ...

Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used: (function poll() { setT ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

Can the chosen date in a calendar date picker be linked to a variable that is accessible to a separate file?

Currently, I am developing a React application and have integrated a date picker feature using Ant Design to enable users to select a date range. My goal is to store the selected date value into a variable that can be accessed by another file in my progr ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

Display a hidden div upon loading the page if a certain condition is met

As a beginner in this field, I am struggling to assist a friend with a project. He needs a simple quote form that can generate HTML quotes for his client on a private WordPress page. The form should display a specific div based on the radio button selecti ...

Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative. Current code snippet: var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxx ...