I'm building a form in Laravel's Blade syntax, and using AlpineJs for some interactivity stuff like showing and hiding content.
My code is here:
<div x-data="destinationBuilder">
<x-label required="true" >Destination:</x-label>
<x-basic-input @change="handleDestinationChange" ::value="destination" placeholder="https://google.com"/>
<x-buttons.primary @check="validateDestination">Check</x-buttons.primary>
</div>
<div >
<button type="button"
@click.camel="toggleAdvancedOptions">
<i ></i>
<span >Advanced options</span>
<div ></div>
<i ></i>
</button>
<div x-show="advanced" x-transition x-cloak>
{{-- <x-links.get-parameter-form/>--}}
</div>
</div>
@push('footer-scripts')
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('destinationBuilder', () => ({
destination: '',
advanced: false,
handleDestinationChange() {
if (this.validateDestination()) {
// emit constructed destination up
}
},
validateDestination() {
// check url is in a legit form (with https)
// basic is just url input
// advanced dropdown with get parameters, fragment, http protocol and port
},
toggleAdvancedOptions() {
this.advanced = !this.advanced;
}
}));
})
</script>
@endpush
I'm using a property named advanced
to bind to x-show for another component.
When I look in my browser I get the following message: app.js:434 Uncaught ReferenceError: advanced is not defined
I'm not sure if this is due to a weird collision with blade or if I'm missing something fundamental with Alpinejs. I tried renaming the variable to showAdvanced
but that didn't work either. I would expect advanced to be recognised as a property and bind to x-show as expected. What am I doing wrong here?
CodePudding user response:
You have the following HTML structure:
<div x-data="destinationBuilder">
...
</div>
<div>
<div x-show="advanced">
...
</div>
</div>
As you see, the second div is not a child element of the first one where the x-data
is defined, so it's outside of the scope of destinationBuilder
component. Just create a common div (or similar) element that embeds both divs and apply the component x-data
there, so each div will have access to the component's scope.