在Vue JS组件中使用Laravel路由的最佳方法是什么

The*_*M97 6 laravel vue.js

我有一个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');
});
Run Code Online (Sandbox Code Playgroud)

Vue组件:

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

}

它现在有效,但我想知道这是最好的方式还是有更好的方法来做到这一点

Cod*_*rts 8

您可以将路径作为props传递给刀片文件中的组件.

在视图内:

<component home-route="{{ route('home') }}"></component>
Run Code Online (Sandbox Code Playgroud)

在vue组件内:

<script> 
    export default {
        props: ['homeRoute'],
    }
</script>
Run Code Online (Sandbox Code Playgroud)

然后你可以访问组件内的路由,如下所示:

this.homeRoute
Run Code Online (Sandbox Code Playgroud)

您可以在此处了解有关道具的更多信息:https://vuejs.org/v2/guide/components-props.html

希望这可以帮助.

  • 但是,如果我要使用需要参数的路由? (6认同)
  • @john &lt;组件 home-route="{{ 路线('home', $parameters) }}"&gt;&lt;/组件&gt; (2认同)
  • @SamuelAialaFerreira 如果参数应该从 vue 应用程序传递怎么办? (2认同)
  • 他们的意思是“如果 $parameters 变量需要来自 Vue 应用程序并且在页面首次加载时未知怎么办?” (2认同)