Alpine.js - show/hide div 基于 select 输入值

Alpine.js - show/hide div based from select input values

我正在尝试根据 select 框 selected 值显示和隐藏 div。我的 select 盒子在工作,所以它会像这样更改值:

// x-data="{ week: false, day: false }

            <select @change="week = $event.target.value">
                <option x-bind:value="Week 1">Week 1</option>
                <option x-bind:value="Week 2">Week 2</option>
                <option x-bind:value="Week 3">Week 3</option>
            </select>
            <select @change="day = $event.target.value">
                <option x-bind:value="1">Monday</option>
                <option x-bind:value="2">Tuesday</option>
                <option x-bind:value="3">Wednesday</option>
                <option x-bind:value="4">Thursday</option>
                <option x-bind:value="5">Friday</option>
            </select>
            <span x-text="'option '+ week"></span>
            <span x-text="'option '+ day"></span>

然后我尝试根据 select 离子显示和隐藏 divs,但没有运气。

<div :class="week !== {{ $week['name'] }} ? 'hidden' : 'block'">
     <p>{{ $week['name'] }}</p>
</div>

如何正确设置class?或者我可以使用 x-show 来做到这一点吗?

从后端模板系统插入字符串时,必须确保将其放置在正确的环境中。 Blade并不知道你真正要生成JS代码,它只是解析了模板的Blade-specific部分。在 :class 属性中,您缺少 {{ $week['name'] }} 两边的引号。 Blade 只是插入字符串,例如Week 1 但您必须在其周围添加引号才能创建有效的 JS 代码。是的,您可以对 hide/show 内容使用 x-show 指令。此外,对于输入元素,您可以使用 x-model directive.

而不是 @change
<!-- Assuming you have 'week' and 'day' in x-data -->
<select x-model="week">
    <option x-bind:value="Week 1">Week 1</option>
    <option x-bind:value="Week 2">Week 2</option>
    <option x-bind:value="Week 3">Week 3</option>
</select>
<select x-model="day">
    <option x-bind:value="1">Monday</option>
    <option x-bind:value="2">Tuesday</option>
    <option x-bind:value="3">Wednesday</option>
    <option x-bind:value="4">Thursday</option>
    <option x-bind:value="5">Friday</option>
</select>    

<div x-show="week === '{{ $week['name'] }}'">
    <p>{{ $week['name'] }}</p>
</div>