laravel-route-scripts v1.0.8
Laravel Route Scripts
This package helps to execute Javascript with all the power of laravel mix webpack in your Laravel Named Routes.
Sometimes you don't have a running SPA in your Laravel app but you want to run modern javascript with laravel mix workflow on specific pages to ad some vuejs interactions. If that's the case this package can help you.
Installation
- Install as dependency:
npm instal laravel-route-scripts --save-dev
or
yarn add laravel-route-scripts --dev
Usage
In your main view layout blade file you must set to any element the attribute:
data-laravel-route-name="{{ Route::currentRouteName() }}"
. You can get all your routes name by runningphp artisan route:list
.Then just need to create a javascrtipt file on any location inside
resources/js
and import it in your mail js file.Import in your new file the library. Example:
import LR from 'laravel-route-scripts'
.In the new file create a new instance
new LR('laravel.name.route').onInit(() => { console.log('js code here') })
, if you need to run the same code on several routes you can also use an array of route names in the constructor function.You can chain this methods:
onInit
ordocReady
with a callback with your code.
How it works
php artisan route list
- Run this command to locate your target route name in this example we use: contributors.photos.create
data-laravel-route-name="{{ Route::currentRouteName() }}"
will create this attribute.New imported file example.
import LR from 'laravel-route-scripts';
import Vue from 'vue'
// pass the route name or array of route names ['contributors.photos.create', 'contributors.photos.show']
new LR('contributors.photos.create')
.onInit((lr) => {
console.log('This run immediately javascript executes')
// you can start vue here liks `new Vue(options)` or use lr initVue helper
// with the lr reference you can access to the current instance also
lr.initVue(Vue, {
el: '#frontend-vue',
data () {
return {
title: 'title'
}
},
})
// helper function to check if you are in specific route, handy when you are running in multiple routes
console.log(lr.isRoute('contributors.photos.create'))
}).docReady((lr) => {
console.log('This runs when the DOM is ready')
console.log(lr.$vi); // access the created vuejs instance
})
Available API:
NOTES:
onInit
anddocReady
have access to receive an parameter that reference the instance itself.
License
MIT