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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With