首页 > 解决方案 > Alpine.js 将 select 的变化绑定回 x-data

问题描述

我有两个 @click 指令的锚标记?更新我的选择选项。我希望在选项发生更改时将 activeTab 的值更新为 0 或 1。我一直在尝试 @change 但没有任何乐趣。提前致谢

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
<div x-data="{activeTab : window.location.hash ? window.location.hash.substring(1) : 0, lessons:[{id:0,room:'online',description:'Online description'},{id:1,room:'in class',description:'in class description'}]}" x-init="select = lessons[0].room" class="w-full">
  <nav class="w-full flex flex-no-wrap justify-between mb-8">
    <template x-for="lesson in lessons">
      <a href="#" @click.prevent="activeTab = lesson.id; window.location.hash = 0; select = lesson.room" class="focus:outline-none focus:text-teal-800 hover:text-teal-800 meta bold py-1 uppercase mr-1 flex items-center justify-between text-lg w-1/2 border-b-4 focus:border-teal-800 hover:border-teal-800 border-teal-600 tracking-widest text-teal-600"><span x-text="lesson.room"></span><svg class="w-6 h-6" width="6" height="6" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg">
          <path d="m8.5.5-4 4-4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" transform="translate(6 8)" /></svg></a>
    </template>
  </nav>
  <template x-for="lesson in lessons" :key="lesson.id">
    <div x-show="activeTab === lesson.id">
      <p x-text="lesson.description" class="text-gray-800 mb-6">Online classes are streaemed to your device. You can atned a yoga class wherever there is a why-fi</p>
    </div>
  </template>

  <form action="">
    <fieldset class="border p-4">
      <legend class="text-center text-xs uppercase tracking-widest text-orange-800 px-2">choose a classroom</legend>
      <select class="relative uppercase text-lg tracking-widest text-teal-800 w-full border border-teal-800 px-5 py-4 focus:outline-none focus:border-shadow rounded" name="" id="" x-model="select">
        <template x-for="lesson in lessons" :key="lesson.id">
          <option :id="lesson.id"><span x-text="lesson.room"></span></option>
        </template>
      </select>
    </fieldset>
  </form>
</div>

标签: alpine.js

解决方案


推荐阅读