【问题标题】:What is the best way to use Laravel route in Vue JS component在 Vue JS 组件中使用 Laravel 路由的最佳方法是什么
【发布时间】: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 watchnpm run hot,这将自动重新编译您的 JS,包括新路由,只要您在 javascript 中的某处执行类似 require('routes.js)` 的操作。

标签: laravel vue.js


【解决方案1】:

您可以将路由作为道具传递给刀片文件中的组件。

视图内部:

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

vue 组件内部:

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

然后你可以像这样访问组件内部的路由:

this.homeRoute

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

希望这会有所帮助。

【讨论】:

  • 但是如果我想使用需要参数的路由呢?
  • @john
  • @SamuelAialaFerreira 如果参数应该从 vue 应用程序传递怎么办?
  • @Yerke 不明白你的意思很遗憾:(
  • 它们的意思是“如果 $parameters 变量需要来自 Vue 应用程序并且在页面首次加载时不知道怎么办?”
【解决方案2】:

我发现使用带参数的路由的唯一方法是这样的:

路线:

Route::get('route/{param1}/{param2}', [Controller::class, 'actionName'])->name('routeName');

刀片:

<component :route="'{{ route('routeName', ["", ""]) }}'"></component>

数组中空字符串的数量等于路由所需参数的数量。

组件:

<script>
export default {
    props: {
        route: String
    },
    data() {
        return {
            param1: "",
            param2: ""
        }
    },
    computed: {
        fullRoute() {
            return this.route + '/' + this.param1 + '/' + this.param2;
        }
    }
}
</script>

我正在使用 Laravel 8 和 Vue 3。

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 2020-02-12
    • 2015-08-14
    • 2018-05-03
    • 2015-03-20
    • 2019-10-30
    • 2015-09-05
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多