【问题标题】:AlpineJs - iterate only not null valuesAlpineJs - 仅迭代非空值
【发布时间】:2022-02-06 02:18:31
【问题描述】:

我正在使用 Laravel8 和 AlpineJs2。我想使用 Alpine 进行有条件的下拉菜单。 我有两个问题:

  1. 我想为每个选择的孩子呈现一个 customClass,例如。 :class="selectChild{parent.id}"
  2. 我只想在 parent.children.length > 0 时呈现选择

感谢您的回答

$data = [
    [
        'id' => 1,
        'name' => 'Parent1 Name',
        'children' => [],
    ],
    [
        'id' => 2,
        'name' => 'Parent2 Name',
        'children' => [
            [
                'id' => 1,
                'name' => 'Parent2Child1 Name',
            ],
            [
                'id' => 2,
                'name' => 'Parent2Child2 Name',
            ],
            [
                'id' => 3,
                'name' => 'Parent2Child3 Name',
            ],
        ],
    ],
    [
        'id' => 3,
        'name' => 'Parent3 Name',
        'children' => [
            [
                'id' => 1,
                'name' => 'Parent3Child1 Name',
            ],
            [
                'id' => 2,
                'name' => 'Parent3Child1 Name',
            ],
        ],
    ],
];

和模板:

    <div class="row"
         x-cloak
         x-data="{
            data: {{ json_encode($data) }}
         }"
    >
        <div class="col-4">
            <select class="form-select selectParent">
            <template x-for="parent in data" :key="parent.id">
                <option :value="parent.id" x-text="parent.name"></option>
            </template>
            </select>
        </div>
        <div class="col-4">
            <template x-for="parent in data" :key="parent.id">
                <select x-if="parent.children.length"  :class="selectChild{parent.id}"  class="form-select">
                    <template x-for="child in parent.children" :key="child.id">
                        <option :value="child.id" x-text="child.name"></option>
                    </template>
                </select>
            </template>
        </div>
    </div>




【问题讨论】:

    标签: laravel-8 alpine.js


    【解决方案1】:

    目前我发现的最佳解决方案:

    <select x-show="parent.children.length" :class="`form-select selectChild${parent.id}`">
       <template x-for="child in parent.children" :key="child.id">
          <option :value="child.id" x-text="child.name"></option>
       </template>
    </select>
    

    我对 className 很满意,但我不喜欢必须渲染元素并将其隐藏的事实...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 2020-06-03
      • 2021-10-15
      • 2017-04-20
      相关资源
      最近更新 更多