Home  >  Q&A  >  body text

Vue: Dropdown menu transition and how to switch the class of another element

I got this (very simple):

<div class="dropdownMenuWrapper">
  <ul class="dropdownMenu">
    <li class="dropdownMenuItem"> Menu 1 </li>
    <button class="arrow" @click="toggleActive">></button>
  </ul>
</div>

<div class="dropdownListWrapper">
  <ul class="dropdownList">
    <li class="dropdownItem">DropdownItem</li>
    <li class="dropdownItem">DropdownItem</li>
    <li class="dropdownItem">DropdownItem</li>
  </ul>
</div>

I want to write a dropdown menu that opens with a transition. So the height will change from 0 to 100 pixels in a 1 second transition.

So I think switching the class of dropdownList is a good way. Am I right? First it gets the class with a height of 0, and after clicking the arrow it gets the class with a higher height.

My question: How to toggle this class using click event on arrow?

P粉754473468P粉754473468182 days ago378

reply all(1)I'll reply

  • P粉676588738

    P粉6765887382024-04-01 20:06:25

    Answer: Use class binding

    Since it's not clear which Vue version you are using, I assume you are using vue3.

    In the script tag, add the Ref to be referenced in the template section. Since you are only checking if the button was clicked, use boolean type.

    const isActive = ref(false)
    

    Then use class binding (add : in front of the class attribute) by using isActive Conditionally put classes on tags en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator" rel="nofollow noreferrer">JS ternary

    Basically, if isActive is true, it will put active-dropdown-list on that element, otherwise it will be inactive-dropdown-list

    reply
    0
  • Cancelreply