是否可以在 for 循环中使用 Alpine.js 在 img 中的 src 中注入变量?

Is it possible to inject variable inside src in img with Alpine.js from a for loop?

我是 运行 一个带有 Alpine.js 的 for 循环。我正在使用 Nunjucks 模板引擎。

我有一个包含三个项目的数组,名为 items

是否可以在img标签的src属性中注入item变量?请参阅下面的代码。

<div x-data="{items: ['first-image.png','second-image.png','third-image.png'], active: 0}">
<div class="snap overflow-auto relative flex-no-wrap flex transition-all" x-ref="slider"
    x-on:scroll.debounce="active = Math.round($event.target.scrollLeft / ($event.target.scrollWidth / items.length))">
    <template x-for="(item,index) in items" :key="index">
        <div class="w-full flex-shrink-0 flex items-center justify-center">
            <img src="`../assets/images/favicon/${item}`" alt="" style="height:550px">
        </div>
    </template>
</div>

绝对有可能,您正在寻找的是 x-bind 指令。

您可以使用 shorthand[=15 中的 x-bind:src="someValue":src="" 将 Alpine.js 组件状态的值“绑定”到 src 属性=]

所以你可以这样做:

<img x-bind:src="`../assets/images/favicon/${item}`" alt="" style="height:550px">