Alpine V3 : Unable to access x-data component values since I upgraded Hello,
Since I updated Alpine I'm unable to access x-data object, I changed like mentionned in the documentation
but i get this error : caught ReferenceError: test is not defined
<div x-data="test">
<span @click="prout" x-text="">coucou</span>
</div>
@endsection
@push('scripts')
<script src="{{asset('js/home/home.js')}}"></script>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data("test", () => ({
text: "salut",
prout: () => {
this.text = "oups!"
}
}))
})
In Alpine.js v3, the Alpine.data() method has been replaced with Alpine.data() function. Therefore, the code should be updated as follows:
<div x-data="test">
<span @click="prout" x-text="text">coucou</span>
</div>
@push('scripts')
<script src="{{asset('js/home/home.js')}}"></script>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('test', () => ({
text: 'salut',
prout() {
this.text = 'oups!';
}
}));
});
</script>
@endpush
not working... thanks chtaGPT :(
@Elo ïse something like this ?
<div x-data="{ text: 'apple', prout(fruit) { this.text = fruit} }" class="space-x-4">
<button @click="prout('banana')">banana</button>
<button @click="prout('orange')">orange</button>
<span x-text="text"></span>
</div>
Thanks for your reply this works but what if I want to have x-data outside in a script ? If I made that I got the previous error message
this should work but it doesn't :
caught ReferenceError: test is not defined
<div x-data="test" class="space-x-4">
<button @click="prout('banana')">banana</button>
<button @click="prout('orange')">orange</button>
<span x-text="text"></span>
</div>
@endsection
@push('scripts')
<script src="{{asset('js/home/home.js')}}"></script>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('test', () => ({
text: 'apple',
prout(fruit) {
this.text = fruit
}
}));
});
@Elo ïse
<div x-data="test" class="space-x-4">
<button @click="prout('banana')">banana</button>
<button @click="prout('orange')">orange</button>
<span x-text="text"></span>
</div>
@push('scripts')
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('test', () => ({
text: 'apple',
prout(fruit) {
this.text = fruit
}
}))
})
</script>
@endpush
My bad ! I've forget to add window.Alpine = Alpine in app.js
@Elo ïse oops i guess you are missing close tag, nvm
If you're loading Alpine through NPM rather than a CDN, then inline scripts are not the place to register Alpine data.
This goes for all Apline data (data, stores, binds, directives, magics, etc)
@cwhite I mix this in another js inline file and finally use it in the view so it's not used on every pages.
Please sign in or create an account to participate in this conversation.