How can I set the first matched value in a Vue (Element UI) dropdown as the default selection?

Framework used: Vue and Element UI

Mission: The goal is to have the first matched value displayed by default.

Issue: When selecting Texas from the common states, it displays Texas from all states in the dropdown when opened. Both should be selected as they have the same values, which is correct. The functionality works correctly.

Approach: I attempted to hide the list of all states when the value is present in the common states, but this did not achieve the desired result.

Desired Outcome: If Texas is selected and is in the common states, I want it to be shown as default when opening the dropdown (in the common states section instead of the all states section). Is there a way to accomplish this?

Link to Codepen: https://codepen.io/limbe_me/pen/BaMwRNz

Boilerplate:

<template>
  <div>
    <el-select v-model="selectedState" placeholder="Select a state">
      <el-option-group label="common states"&gsoiacvvendash;>
        <el-option
          v-for="item in commonStates"
          :label="item"
          :key="item + '_common'"
          :value="item"
        ></el-option>
      </el-option-group>
      <el-option-group label="all states">
        <el-option
          v-for="item in allStates"
          :label="item"
          :key="item + '_all'"
          :value="item"
        ></el-option>
      </el-option-group>
    </el-select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedState: "",
      commonStates: ["California", "New York", "Florida", "Texas", "Hawaii"],
      allStates: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        ".....",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming"
      ]
    };
  },
  methods: {
    // Your methods go here
  }
};
</script>

Answer №1

You have the option to achieve it in this way

<template>
  <div>
    <el-select v-model="selectedState" placeholder="Select a state" @visible-change="change">
      <el-option-group label="common states">
        <el-option
          v-for="item in commonStates"
          :label="item"
          :key="item + '_common'"
          :value="item"
        ></el-option>
      </el-option-group>
      <el-option-group v-if="enabled" label="all states">
        <el-option
          v-for="item in allStates"
          :label="item"
          :key="item + '_all'"
          :value="item"
        ></el-option>
      </el-option-group>
    </el-select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      enabled: false,
      selectedState: "",
      commonStates: ["California", "New York", "Florida", "Texas", "Hawaii"],
      allStates: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        ".....",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming"
      ]
    };
  },
  methods: {
    // Your custom methods can be defined here
    change(isVisible) {
      this.enabled = isVisible
    }
  }
};
</script>

<style>
.app {
  color: black;
}
</style>

Add v-if="enabled" to your allStates option group. Ensure to set it as true when the dropdown is visible

As per the ElementUI documentation, you can utilize the visible-change event and assign the value of $event to the variable enabled

Here's the link to the Codepen: https://codepen.io/duckstery/pen/QWYqOQo


In response to your additional request for customization, I've made some adjustments to my code

  data() {
    return {
      enabled: true,
      selectedState: "",
      commonStates: ["California", "New York", "Florida", "Texas", "Hawaii"],
      allStates: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        ".....",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming"
      ]
    };
  },
  methods: {
    // Your custom methods go here
    change(isVisible) {
      if (this.commonStates.includes(this.selectedState)) {
        this.enabled = false;
        this.$nextTick(() => (this.enabled = true));
      }
    }
  }

The initial value of enabled is now set to true

It's important to check whether the selectedState exists within the array commonStates. If so, update the value of enabled accordingly and handle this with $nextTick

Find the updated version on Codepen: https://codepen.io/duckstery/pen/wvNrmMm

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

Mastering the art of implementing dynamic template variables in TinyMCE

After exploring the 'full' example and conducting research on the Wiki and moxie forums, I have yet to find a solution. I am attempting to implement what the wiki states is possible, but encountered an issue when replacing the 'staffid' ...

Tips for extracting data from an HTML form using AJAX

Currently working on a project in Django for a car rental/sale web application. The search query within the app is functioning correctly, however, when attempting to submit the form using AJAX, it appears that the request never reaches into the AJAX portio ...

React mapped checkboxes are displaying all elements from the array, not just the ones that are checked

Visual: The form is displayed on the left, while the outputs appear on the right I'm currently working on implementing a checkbox array map in React to showcase the features of a specific item. However, I'm facing an issue where all array elemen ...

Issue in TypeScript: Property '0' is not found in the type

I have the following interface set up: export interface Details { Name: [{ First: string; Last: string; }]; } Within my code, I am using an observable configuration variable: Configuration: KnockoutObservable<Details> = ko.observable& ...

What is the best way to compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Tips for showcasing an image on an HTML page

I am encountering an issue with my HTML page that includes a Button. When clicked, it is supposed to display an image using an Ajax call. The functionality works properly in Postman Rest Client. However, when accessed through a browser, it only shows raw ...

How can we determine if a v-for loop in Vue.js that includes a v-if condition has rendered any elements?

In the scenario where the code below is implemented: <template v-for="(item, index) in items" v-if="item.name === 'foo'"> <p>{{ item.name }}</p> </template> Is there a way to display a message if this loop doesn' ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

element with singular border

I overlaid one div on top of another to create a border effect. Check out this example: However, I am facing an issue: when I hover the mouse over the image, only the div with the border gets focus (for instance, for right-clicking and saving the image), ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

Discord.js Lock Command Implementation

I've developed a lock command for discord.js, but every time I try to run the command, I encounter an error. Here's the code snippet: module.exports = { name: "lock", description: "Lock", async run(client, message ...

Tips for utilizing a Map instance in JSX?

Is there a more efficient method for iterating over a Map object in JSX? const map = new Map<string, string[]>([ '2023-08-23': ['string1', 'string2'], '2023-08-24': ['string3', 'string4' ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

Ember's route-refreshing event

Exploring the possibility of displaying a modal when a specific route is refreshed in an ember app. The modal will offer an 'ok' action to proceed with the refresh and a 'cancel' action to stop it. Although Ember has a 'refresh()& ...

Navigating through the conditional "where" clause in IndexDB for various browsers

I have successfully implemented indexdb because it provides support for all browsers. I have managed to add and retrieve data from indexdb, but now I want to implement a where clause condition. For example, I have fields like Product Name, Pathogen, Diseas ...

Experiencing difficulties integrating Python Requests with the Bonanza API in Node.js due to a lack of proper documentation and inability to make successful API

I've been following the Bonanza.com Bonapitit documentation and managed to make their Python fetchToken script work. However, I'm now attempting to replicate this script in Node.js for my ExpressJS backend instead of using Python. Here's ho ...

Using jQuery to load an HTML page into a specified div element

I've encountered an issue while trying to load an html page within a div using the following code: $("#page1").html('<object data="http://stackoverflow.com/">'); The problem I am facing is that the loaded page appears very small in t ...

Utilizing Cowboy as the HTTP web server for Express JS

Many websites are utilizing Cowboy as the HTTP Web server and Express JS as the Web application server. They typically have their HTTP header set to Cowboy for the server, with the X-Powered-By HTTP header indicating Express. One example is This setup rai ...