在 Vue JS 组件中使用 Laravel 路由的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46940318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to use Laravel route in Vue JS component
提问by TheAngelM97
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:
我有一个 vue js 组件,它向 laravel 路由发出 axios 请求。但是在 vue 文件中,我无权访问该route()
函数,现在必须使用静态 url。这是一些代码: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:
Vue 组件:
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
它现在有效,但我想知道这是最好的方法还是有更好的方法来做到这一点
回答by Codearts
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:
在 vue 组件内部:
<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
您可以在此处了解有关道具的更多信息:https: //vuejs.org/v2/guide/components-props.html
Hope this helps.
希望这可以帮助。