【问题标题】:Alpine JS - Creating a menu with active statesAlpine JS - 创建具有活动状态的菜单
【发布时间】:2021-07-11 22:28:54
【问题描述】:

我正在尝试使用 Alpine JS 创建侧边栏菜单

我什至不确定这是否可能与 Alpine JS 相关。

@foreach($kanbans as $kanban)
  <div x-data="activeKanban : ????">
    <div @click="activeKanban = {{$kanban->id}}">

       <div x-show="activeKanban !== {{$kanban->id}}">
        // Design for collapsed kanban
       </div>

    <div>

    <div x-show="activeKanban === {{$kanban->id}}">
        // Design for active kanban
    </div>

  </div>
@endforeach

当我切换页面时,$kanban-&gt;id 发生了变化,我想知道除了手动设置 activeKanban : 1 之外,有没有办法将此信息传递给 AlpineJS?

所以默认情况下,如果我加载其他页面,将打开的默认菜单将基于 ID,而不是全部折叠或仅指定打开的 1?

【问题讨论】:

    标签: laravel laravel-livewire alpine.js


    【解决方案1】:

    如果您的目标是各种手风琴菜单,那么您可以根据您共享的代码使用 AlpineJs 实现它:

    // Set x-data on a div outside the loop and add your active kanban as a property
    <div x-data="{
        activeKanban: {{ $activeKanbanId ?? null }}
    }">
        @foreach($kanbans as $kanban)
            <div @click="activeKanban = {{ $kanban->id }}">
                <div x-show="activeKanban !== {{ $kanban->id }}">
                    // Collapsed view
                </div>
    
                <div x-show="activeKanban === {{ $kanban->id }}">
                    // Expanded view
                </div>
            </div>
        @endforeach
    </div>
    

    这里每个看板菜单项都可以访问 AlpineJs 组件实例中的activeKanban 属性,并且可以进行响应式设置。

    即如果 activeKanban 设置为新的 id,当前打开的项目将关闭,新的项目将打开


    增加灵活性

    如果你想独立打开和关闭它们怎么办?实现这一点的方法不止一种,但在这种情况下,我们可以修改上面的代码以允许它:

    // Here we add an array of openItems and two helper functions:
    // isOpen() - to check if the id is either the activeKanban or in the openItems array
    // toggle() - to add/remove the item from the openItems array
    <div x-data="{
        activeKanban: {{ $activeKanbanId ?? null }},
        openItems: [],
    
        isOpen(id){
            return this.activeKanban == id || openItems.includes(id)
        },
        toggle(id){
            if(this.openItems.includes(id)){
                this.openItems = this.openItems.filter(item => {
                    return item !== id
                });
            }else{
                this.openItems.push(id)
            }
        }
    }">
        @foreach($kanbans as $kanban)
            <div @click="toggle({{ $kanban->id }})">
                <div x-show="!isOpen({{$kanban->id}})">
                    // Collapsed view
                </div>
    
                <div x-show="isOpen({{$kanban->id}})">
                    // Expanded view
                </div>
            </div>
        @endforeach
    </div>
    

    这允许我们设置一个活动项,也可以选择打开/关闭其他菜单项。

    【讨论】:

    • 哇!十分感谢你的帮助! :)
    • 没问题??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多