Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
Is it possible to create dynamic inline bindings with Alpine.js?

I would like to create a dynamic :class or :style binding that uses data stored in an Alpine.js variable.

<div x-data="{ divClass: 'inner', color: 'red' }">
  <div :class="${divClass}"
       :style="background-color: ${color}"></div>
</div>

In the example above, I would like the divClass variable to output a dynamic class inner, and the color to output a dynamic style red — is it possible?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As of August 2021, it is not possible to do it directly. However, there are two possible solutions (mentioned in this issue, in the Alpine.js repository).

The hacky way

There is a simple hack you can use to achieve what you want, you simply need to wrap the values of the attributes in backticks:

<div x-data="{ divClass: 'inner', color: 'red' }">
  <div :class="`${divClass}`"
       :style="`background-color: ${color}`"></div>
</div>

The libraries

There are two libraries that help wrap dynamic classes/styles in a nice-looking code. They are classnames and stylenames. With them on board, the code could look something like this:

<div x-data="{ divClass: 'inner', color: 'red' }">
  <div :class="classNames( divClass )"
       :style="styleNames({ backgroundColor: color })"></div>
</div>
A biased disclaimer

In my opinion, the first solution is better as it saves precious kB by not adding additional dependencies. However, you need to take into consideration that it's slightly less legible and potentially confusing for other developers.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda