【问题标题】:Using Laravel defined routes within a VUE component在 VUE 组件中使用 Laravel 定义的路由
【发布时间】:2020-10-31 15:25:14
【问题描述】:

我正在使用 Laravel 6 和 VUE。我正在将刀片文件转换为 VUE 组件。刀片文件包含一个表,其中包含从 mysql 数据库中提取的数据行。我创建了一个显示用户的可拖动组件,并允许我拖放行以重新排列它们,并且该表使用 VUE 插槽将 html 传递给我的组件。在我的索引视图中,表格上有一个按钮。单击该按钮时,它会转到我在 Laravel 中使用 routes.php 文件定义的 /create 端点/路由。我不想使用 vue 路由,我更喜欢按原样维护我的 laravel 路由。我遇到的问题是,我不知道如何完全实现这一点,因为我是 VUE 的新手。有人可以对此有所了解吗?我尝试使用 axios 但也许我用错了?有没有更好的方法来使用 vue 组件但继续使用我在 routes.php 中定义的路由?谢谢。

main.blade.php

 <!-- Draggable Component -->
            <div id="app">
                <draggable table=@yield('content.main')></draggable>
            </div>

routes.php(部分显示我想要访问的端点)

  $route->any('users/create', 'UsersController@create');

可拖动的.vue

<template>
    <section v-bind:table="table">
        <button class="btn btn-default" @click="create()">
            <i class="fa fa-plus"></i>
        </button>
        <slot></slot>
    </section>
</template>

<script>
   export default {
       props: ['table'],
       data() {
           return {
               draggable: '',
           };
       },
       created() {
           this.draggable = this.table;
       },
       methods: {
           create() {
               axios.get(this.endpoint, {
                   UserName: this.UserName
               }).then(res => {
                   this.creating = true;
                   this.UserName = res.data.UserName
               }).catch(err => {
                   console.log("Error: " + err);
               })
           },
       },
       computed: {
           endpoint() {
               return `users/create`;
           },
       }
   };
</script>

点击按钮时出现的错误:

 Error: Request failed with status code 404

【问题讨论】:

  • 如果你想在你的 laravel 路由中使用 vue,那么结合刀片和 vue。
  • 嗨@JesusErwinSuarez你能详细说明一下吗?或者提供一个例子或指向我正确的文档?谢谢。

标签: laravel vue.js axios laravel-blade


【解决方案1】:

在您的endpoint() 中,您可以添加window.location.protocol + "//" + window.location.host,这样方法就可以了

endpoint() {
    return window.location.protocol + "//" + window.location.host + 'users/create';
},

【讨论】:

  • 我在端点方法中添加了这个。该页面没有重定向到 /create 页面??在我的浏览器控制台中,我确实收到了 200 响应,并且在“网络”选项卡的“预览”选项卡中,显示了 /create 页面。但是在实际的浏览器本身中,没有发生 REDIRECT,所以页面没有改变……这是为什么呢?
  • 好吧,明确一点,当您按下创建按钮时,您需要重定向到 /users/create 并从此端点获取数据?
  • 对不起,如果我感到困惑。我想要的是:单击按钮时,我只想重定向到 /create 页面。
  • 好的,在这种情况下,您不需要axios 调用,因为您不获取任何数据,您需要使用window.location = window.location.protocol + "//" + window.location.host + 'users/create';,我认为您也可以内联。
  • 在您的 create 方法中仅添加 window.location = this.endpoint();
猜你喜欢
  • 2018-10-15
  • 2021-11-16
  • 2021-05-01
  • 2018-01-05
  • 1970-01-01
  • 2018-05-23
  • 2019-02-05
  • 1970-01-01
  • 2020-02-13
相关资源
最近更新 更多