我有一个vue js组件,它向laravel路由发出axios请求.但在vue文件中,我无法访问route()函数,目前只能使用静态url.

// 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)
                    })
            },
            ...

}

现在可以了,但我想知道这是最好的方法还是有更好的方法

推荐答案

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

在视图内部:

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

在vue组件内部:

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

然后可以访问组件内部的布线,如下所示:

this.homeRoute

你可以在这里了解更多关于props 的信息:https://vuejs.org/v2/guide/components-props.html

希望这有帮助.

Vue.js相关问答推荐

Vue路由路径匹配行为

Vue3:如何在功能组件中重用插槽vnode

为什么我的数组在 onBeforeMount 函数中不为空,但在 onMounted 函数中为空

在预渲染模式下部署 nuxt 3 时出错

Vue3外部数组的响应性

vue3 + pinia:如何从?store 中获取一个值

使用 vue / nuxt js 切换 fontawesome 图标

已分配计算(computed)属性,但它没有设置器

VuetifyJS:如何摆脱 v-stepper 组件的提升?

在组件上的 Vue 3 中获取 URL 查询参数

如何在 vue.js 2 的其他组件中调用方法?

Vue.js 从模板中分离样式

请求正在进行时显示加载器

我可以在 Vue 实例方法中传播的 mapMutations 中使用this吗?

如何在 Vuex 中获取 Vue 路由参数?

将 VueJS 数据属性重置为初始值

错误:找不到模块'@vue/babel-preset-app'

v-for 中的计算(Computed)/动态(Dynamic) v-model 名称

Vue Router beforeRouteLeave 不会停止子组件

在 Vue 中使用事件修饰符 .prevent 提交表单而不进行重定向