0

I am trying a simple dropdown on a vue project. But the dropdown doesnt drop when I click on it. I have put the console inside the function. The message gets displayed on console that means the function is being called. But it doesnt work.

<template>
  <div class="dropdown">
    <button @click="toggleDropdown" class="dropdown-button">
      {{ selectedOption || "Select an option" }}
    </button>
    <ul v-if="isOpen" class="dropdown-menu">
      <li v-for="option in options" :key="option" @click="selectOption(option)">
        {{ option }}
      </li>
    </ul>
  </div>
</template>


<script>
export default {
  name: "DropDown", // Adding name to the component
  data() {
    return {
      isOpen: false,
      selectedOption: null,
      options: ["Option 1", "Option 2", "Option 3"],
    };
  },
  methods: {
    toggleDropdown() {
      console.log("Button clicked");
      this.isOpen = !this.isOpen;
    },
    selectOption(option) {
      this.selectedOption = option;
      this.isOpen = false;
    },
  },
};
</script>

<style scoped>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-button {
  padding: 10px;
  background-color: #3498db;
  color: white;
  border: none;
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.dropdown-menu li {
  padding: 10px;
  cursor: pointer;
}

.dropdown-menu li:hover {
  background-color: #ddd;
}
</style>

When I checked the console, it seems perfectly fine, the click function is called as shows.

enter image description here

4
  • 1
    I couldn't reproduce this, it worked fine for me. Commented Sep 26, 2024 at 3:00
  • I added the picture. can you please check it @La Ngoc Hai Commented Oct 1, 2024 at 1:34
  • Do you mean "drop down" like it having animation? like it doesnt slowly appear or simply doesnt appear at all? Currently I cant find anything wrong with the code, it works well so I need to know what you actually mean. Use dev tool to inspect the <ul> and see if it changes when button is clicked Commented Oct 1, 2024 at 9:39
  • I tried the code separately in online vue editor too. It works fine there,but same code doesnt work in the project. This is very weird Commented Oct 18, 2024 at 1:18

1 Answer 1

0

That's work fine. Could the elements in the dropdown list fall below the other HTML elements?

reproduce dropdown list

Sign up to request clarification or add additional context in comments.

1 Comment

I tried the code separately in online vue editor too. It works fine there,but same code doesnt work in the project. This is very weird.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.