Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - Use Alpine JS to conditionally add CSS class

Using Alpine JS, is there a way to check for sub menus and toggle a class on the parent nav?

I know how to toggle the value of x-data with a click event, is there something I can add to the nested ul to switch the value of x-data from false to true?

Here's an example:

<nav x-data="{subOne: false, subTwo: false}" :class="{ 'has-sub-menu-1': subOne, 'has-sub-menu-2': subTwo}">        
   <ul>
      <li>Menu Item
         <ul>
            <li>Sub Menu 1
               <ul>
                  <li>Sub Menu 2</li>
               <ul>
            </li>
         <ul>
      </li>
   <ul>
</nav> 

I'd like to be able to toggle x-data values to true if there are sub menus.

question from:https://stackoverflow.com/questions/65936485/use-alpine-js-to-conditionally-add-css-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is not enough context in your question to be sure what you are trying to achieve, but I assume you just want subOne to be true when there is a Sub Menu 1, and subTwo to be true when Sub Menu 2 exists.

If you are generating the menu from the backend, why not do something like

<nav class="{{ $menuItem->getSubMenu() ? 'has-sub-menu-1' : '' }}{{ $menuItem->getSubMenu()?->getSubMenu() ? ' has-sub-menu-2' : '' }}"> 
  <ul>
    <li>{{ $menuItem->name }}</li>
    @if ($subMenuItem = $menuItem->getSubMenu())
      <ul>
        <li>{{ $subMenuItem->name }}
          @if ($subMenuItemTwo = $subMenuItem->getSubMenu())
            <ul>
              <li>{{ $subMenuItemTwo->name }}</li>
            </ul>
          @endif
        </li>
      </ul>
    @endif
</nav>

If you are using AlpineJS to actually build the menu from some data source, please include the complete code. In this case, you can build the condition for :class from the data structure you have.

It's actually very hard to give you any suggestions without knowing how the menu is generated, but the pseudoish code above should give you an idea of what your options are.

(Please note that above code uses PHP 8 syntax, if you use Laravel you can use optional($menuItem->getSubMenu())->getSubMenu() instead).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...