【发布时间】:2018-04-07 00:13:50
【问题描述】:
我有一个 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 组件:
methods: {
getBrands: function() {
let app = this
axios.get('/api/brands')
.then(function(response) {
app.brands = response.data
})
.catch(function(error) {
console.log(error)
})
},
...
}
现在可以了,但我想知道这是最好的方法还是有更好的方法来做到这一点
【问题讨论】:
-
我使用this package 并分配给
window变量取得了不错的成功。 -
@Ohgodwhy 那个包看起来不错。我猜您每次更改路线时都需要运行
php artisan laroute:generate? -
@ljubadr 是的,差不多。这真的是我唯一的抱怨
-
@Ohgodwhy 谢谢!我想可以设置某种观察者来运行命令:) 我想这样的东西可能很有用In Linux, how do I run a shell script when a file or directory changes
-
@ljubadr 我也一直在走这条路。我建议using this package 关注您的
routes目录的更改。在侦听器的回调中,您可以运行Artisan::call('laroute:generate')以重新生成路由文件。然后,您可以运行npm run watch或npm run hot,这将自动重新编译您的 JS,包括新路由,只要您在 javascript 中的某处执行类似require('routes.js)` 的操作。