将 class 绑定到 Alpine.js 中的 $el.value

binding class to $el.value in Alpine.js

好吧,我只是在 Codepen 中玩弄 Alpine,了解事情的窍门,但我不知道我在这里做错了什么。使用此示例输入,当我单击它时,它会在文本框中正确记录值。如果我在 :class 属性中放置一个不同的变量,它就可以正常工作。但我无法根据我在文本框中键入的内容应用 类。我想这在现实世界中没有用处,但我想了解我错了什么。

<input type="text" :class="$el.value" @click="console.log($el.value)" />

目前,您的文本框未连接到 Alpine 的内部状态管理,而是由 DOM 处理,它本身没有“反应性”的概念。因此,如果您更改元素的值,Alpine 不知道它应该“重新渲染”该组件。

来自 Alpine 的文档:

Alpine is "reactive" in the sense that when you change a piece of data, everything that depends on that data "reacts" automatically to that change.

就其本身而言,文本框的值不是反应性的,即未连接到 Alpine 的内部状态管理。对于要连接到 Alpine 状态变量的文本框值,您可以使用 x-model 指令。

x-model is two-way bound, meaning it both "sets" and "gets". In addition to changing data, if the data itself changes, the element will reflect the change.

这是一个工作示例:

<script src="//unpkg.com/alpinejs" defer></script>

<style>
  .red {
    color: red;
  }
  
  .bg-yellow {
    background-color: yellow;
  }
</style>

<input type="text" :class="clsText" x-data="{clsText: 'red bg-yellow'}" x-model="clsText" />