How do I access x-data from a function in an external file? #1262
-
I'm just starting out with Alpine.js, I understand the basics but I'm having trouble applying them when moving functions outside of inline script tags. For example, in <div x-data="{ loading: false }"/>
<button
onClick="post()"
:class="{ 'active': loading === true }"
>
Post Comment
</button>
</div> if const postComment = () => {
this.loading = true;
};
window.postComment = postComment; How do I make it so that I've found plenty of examples where functions are kept within |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You shouldn't mix the approaches. If you use Alpine and you decide to use an external file, the whole component needs to be extracted. this on an external function will never be your Alpine scope (this is how javascript works, though). |
Beta Was this translation helpful? Give feedback.
You shouldn't mix the approaches. If you use Alpine and you decide to use an external file, the whole component needs to be extracted. this on an external function will never be your Alpine scope (this is how javascript works, though).
In general, the logic is the same as the index file, you just need to export the component on the window object if you use a bundler like webpack.
See https://codepen.io/SimoTod/pen/QWdBOYP