How to use Alpine.data() in #push within Laravel Blade components? - laravel

With Alpine.js 2 it was possible to develop Blade components with the following structure:
...
<div x-data="myApp()">
...
#once
#push('child-scripts')
<script>
function myApp() {
return {
...
}
}
</script>
#endpush
#endonce
This was great in that it allowed all the code for the component to be defined together.
In Alpine.js 3 this approach of defining functions is deprecated (https://alpinejs.dev/upgrade-guide#alpine-data-instead-of-global-functions). Instead, they should be defined like this:
...
<div x-data="myApp">
...
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('myApp', () => ({
...
}))
})
</script>
However, it states "you need to define Alpine.data() extensions BEFORE you call Alpine.start()". This suggests that with the new approach it is impossible (or at best unreliable) to use #push to add data functions for use in Blade components and, therefore, impossible to keep all the code for a Blade component together.
My code all works fine with Alipne 3, if I use the deprecated approach. If I try to include the new syntax data function via #push, I get "myApp is not defined" JS error from my Blade component.
I am using Alpine.js 3.9 installed as an NPM module. I have also tried using Alpine.js 3 via <script src="https://unpkg.com/alpinejs#3.x.x/dist/cdn.min.js" defer></script>. The result is the same in both cases.
Is there a way to keep all the code together in the Blade component?
UPDATE 25.02.2022
It seems I need to provide more details of what I am doing so here they are.
The relevant bits of my app.blade.php are:
<head>
...
<script src="{{ asset('js/app.js') }}" defer></script>
#livewireStyles
...
</head>
<body>
// HTML/Blade stuff here
#livewireScripts
#stack('child-scripts')
</body>
My app.js is like:
import Alpine from 'alpinejs'
require('./bootstrap');
window.Alpine = Alpine
Alpine.start();
I have also tried:
require('./bootstrap');
import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start();
My Blade component is like this:
...
<div x-data="myApp">
...
#once
#push('child-scripts')
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('myApp', () => ({
...
}))
})
</script>
#endpush
#endonce
When I access a page that uses the Blade component, I get "Uncaught ReferenceError: myApp is not defined".
If I revert my Blade component to the old syntax (as follows) it works with no errors:
...
<div x-data="myApp()">
...
#once
#push('child-scripts')
<script>
function myApp() {
return {
...
}
}
</script>
#endpush
#endonce
The only difference between the working and failing versions is the way in which myApp is defined. The deprecated method works but, with the new method, it doesn't.

Not sure why you would think that using #push is unreliable.
Since the #push directive (like any other blade directive) is evaluated by the blade engine on the server-side, by the time the page loads, anything you push is already there on the page.
One thing to note is that it is important to defer the execution of the javascript assets so that it is executed after the document has been parsed. You can do that by adding a defer attribute like so:
<!DOCTYPE html>
<html>
<head>
...
<script src="{{ mix('js/app.js') }}" defer></script> {{-- or CDN here --}}
</head>
<body>
...
#stack('scripts')
</body>
</html>
// resources/js/app.js
import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start()
I'm already using Alpine v3 this way without any issues.

Related

Laravel View - Import Vue component

Getting to know laravel (using version 6) and i was wondering how i can make sure that my view is using my Vue component? In this case its the HelloWorld.vue component i want rendered in the albums.blade.php view file.
In my app.js i have made sure to register the component like this:
Vue.component('hello-world', require('vue\src\components\HelloWorld.vue').default);
And then im using it like this inside the albums.blade.php:
<hello-world></hello-world> and i have also made sure to include the script tag referring to app.js like this:
<script src="{{ asset('js/app.js') }}" defer></script>
With no success... any inputs?
See my folder structure here
you need to use laravel mix for vue js
Laravel Mix
change your <script src="{{ asset('js/app.js') }}" defer></script>
to <script src="{{ mix('js/app.js') }}" defer></script>
Place check Laravel Mix docs
My personal config using Laravel mix is:
app.js
require('./bootstrap');
import Vue from 'vue';
window.Vue = Vue;
/** Auto register components */
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
// Other things
// ....
const app = new Vue({
el: '#app'
});
albums.blade.php
Place this script tag at the bottom of the page.
<script src="{{ mix('js/app.js') }}"></script>
Then you could use the component like this:
<div>
<hello-world></hello-world>
</div>
Recommendation
Consider learning Laravel 9 instead of Laravel 6. This because 9 is the newest version and also the actual LTS release.

laravel livewire $wire is not defined

I think I have all my imports right, but I'm getting a $wire is not defined error.
This is at the bottom of my master layout blade file:
#livewireScripts
<script src="{{ asset('js/app.js') }}"></script>
#stack('plugin-scripts')
#stack('custom-scripts')
In my livewire component I have this:
#push('custom-scripts')
<script>
$(document).ready(function() {
console.log($wire.find($('#my-div').attr('id')));
});
</script>
#endpush
I was reading that $wire is an Alpine directive, and here's where I'm including Alpine. I can also type Alpine in the console and it is registered, so I believe that's working.
in my bootstrap.js:
import Alpine from 'alpinejs'
window.Alpine = Alpine
window.Alpine.start()
Also if I type Livewire in the console, it returns the Livewire object, so that seems to be getting loaded correctly as well. However, I added this bit to my code and it did nothing:
document.addEventListener('livewire:load', function() {
console.log('livewire loaded'); // Your JS here.
});

#click showing ReferenceError: function is not defined with AlpineJS + Livewire + Laravel

Am totally lost here. I've made multiple applications with Livewire + AlpineJS + Laravel before, but for some reason I cannot get the #click functionality working for functions in this app.
I reduced the code to almost nothing and cannot see the issue. Have looked at other apps where I have #click working.
<div x-data="showAppSettings()">
<div #click="whatever(123)">Click here</div>
<script type="text/javascript">
window.showAppSettings = () => {
return {
showNav: false,
whatever(id)
{
}
};
}
</script>
Upon clicking the click me and triggering the function, I get the error ReferenceError: whatever is not defined.
Works just fine if I do something like #click="alert('hey')"
What am I missing?
The issue was related to including <script src="{{ asset('js/app.js') }}" defer></script>
That file was not even in use. But either way, the error was being triggered by app.js which I realized made no sense since the code was inline.
Upon removing that line, everything works as intended.
It's needed the defer attribute to load fine the alpine script:
<script defer src="https://unpkg.com/alpinejs#3.x.x/dist/cdn.min.js"></script>

Laravel/Vue Component Registration and Vue Instantiation

I am a new VueJs developer and there is something I can’t seem to get my head around: Using multiple single page components in the app.js file.
These are the questions I’m having trouble answering:
Am I supposed to register ALL of my top-level (parent) components in the Vue Instance in the app.js file?
// App.js
import Component1 from './component/C1.vue';
import Component2 from './component/C2.vue';
const app = new Vue({
el: '#app',
components: {All Top Level components here?}
});
If I need another Vue instance in one of my blade.php files. Where do I instantiate it? Is it best practice to only instantiate Vue once (in the el: #app in app.js) – this doesn’t seem right to me, but I’m new so what do I know.
How should I separate my Vue code from my Laravel Code in the main file? (create a separate section?)
<!DOCTYPE html>
<head>
<!-- App.js -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
#yield('content')
</div>
<div id="app2">
<!-- Where can I instantiate this?--> (Question 2)
</div>
</body>
#yield('vueScripts') <-- (Question 3)
</html>
Q1. You should register all your Vue Component that you will be using inside a blade file.
On the resource folder at the app.js
Vue.component('example-component', require('./components/ExampleComponent.vue').default); if you are just using a component on a single parent component you dont need to register the component globally you just register it in the parent component file like so
//On Parent Component file
import ChildComponent from './ChildComponent.vue' //import child component
export default
{ components: { ChildComponent } // child component registration
,
Q2. One Vue instance is enough
Q3. You dont need a vuescript if you are already using a vue component vue scripts should go in the vue component file

How to extend a layout without overwriting the scripts in the layout section (Laravel 5.8)

Ths should be simple enough, but...
I have a layout view dashboard-layout.blade.php with:
#section('headscripts')
<script src="{{ mix('/js/app.js') }}" defer></script>
#show
And a billing.blade.php view that extends the layout file:
#extends('layouts.dashboard-layout')
#section('headscripts')
#parent
<script src="https://js.braintreegateway.com/web/dropin/1.17.2/js/dropin.min.js"></script>
#endsection
The problem is, this only outputs the first script...what am I doing wrong?
You can simply use #stack('name here') instead of #yield('name here')
and use
#push('name here')
// Add Your Script Here
#endpush
instead of
#section('name here')
// Scripts
#endsection
to solve your problem.

Resources