Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to use Laravel route in Vue JS component

Tags:

laravel

vue.js

I have a vue js component which makes an axios request to a laravel route. But in the vue files I don't have access to the route() function and have to use static url's for now. Here's some code: web.php:

// API
Route::group(['prefix' => 'api'], function() {
    // GET
    Route::get('/brands', 'BrandsController@getBrands')->name('api-get-brands');
    Route::get('/{brand_id}/models', 'BrandsController@getModels')->name('api-get-models');
    Route::get('/fuel-types', 'BrandsController@getFuelTypes')->name('api-get-fuel-types');
    Route::get('/gearboxes', 'BrandsController@getGearboxes')->name('api-get-gearboxes');
});

Vue component:

methods: {
            getBrands: function() {
                let app = this
                axios.get('/api/brands')
                    .then(function(response) {
                        app.brands = response.data
                    })
                    .catch(function(error) {
                        console.log(error)
                    })
            },
            ...

}

It works now but I wonder if that's the best way or is there some better way to do it

like image 389
Angel Miladinov Avatar asked Oct 25 '17 19:10

Angel Miladinov


1 Answers

You can pass the route as props to the component inside the blade file.

Inside the view:

<component home-route="{{ route('home') }}"></component>

Inside the vue component:

<script> 
    export default {
        props: ['homeRoute'],
    }
</script>

Then you can access the route inside the component like so:

this.homeRoute

You can learn more about props here: https://vuejs.org/v2/guide/components-props.html

Hope this helps.

like image 74
Codearts Avatar answered Sep 23 '22 11:09

Codearts