kalkatfyodor
A simple example of Alpine.js code is not working properly in Phoenix 1.6 LiveView
Is there an alternative to Alpine.js in Phoenix 1.6?
I am trying to use this simple example:
<div x-data="{ open: false }">
<button x-on:click="open = ! open">Expands</button>
<div x-show="open" x-transition>
Content...
</div>
</div>
But in my heex template file in my live view it is expanded by default, instead of hidden. Why? In a non live view heex template file it works as expected.
Any idea why LiveView expands it by default on entering the page?
If this problem couldn’t be solved, could you suggest an alternative to Alpine.js that works with the latest Phoenix 1.6 LiveView?
Marked As Solved
shd42
The thing is, for Alpine et LiveView to work properly together, you need to plug Alpine into the LiveSocket like this:
import Alpine from "alpinejs";
window.Alpine = Alpine;
Alpine.start();
let liveSocket = new LiveSocket("/live", Socket, {
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) { window.Alpine.clone(from, to) }
}
}
})
It might be that once the Livesocket connects, and sends back the result, it overrides Alpine applied styles (display: none; in this case), and since Alpine isn’t aware of it, it can’t stop it from happening.
Also Liked
kalkatfyodor
YES!!! It finally works. Thanks a lot.
For people who will encounter similar problem your app.js should look something like this:
Also, don’t forget to download the alpine.js file and save it in assets/vendor/ folder as alpine.js or something like that.
import topbar from "../vendor/topbar";
import Alpine from "../vendor/alpine";
// Alpine
window.Alpine = Alpine;
Alpine.start();
let csrfToken = document
.querySelector("meta[name='csrf-token']")
.getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {
params: { _csrf_token: csrfToken },
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to);
}
},
},
});
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









