【问题标题】:Views Not Creating in Custom Routes in Laravel + Vue.Js在 Laravel + Vue.Js 的自定义路由中未创建视图
【发布时间】:2018-06-28 14:14:01
【问题描述】:

我正在使用 Laravel 5.5 和 Vue.js 2.0
当我打开 example.com 并点击 Display Items 然后这个 url 触发
example.com/items
这是结果


当我直接打开这个 url example.com/items 时,它只显示我从 Laravel 获得的 json 响应,而没有在 html (Vue.js) 中创建任何视图。 见下文:


如何在不先访问 example.com 的情况下访问直接 URL(如 example.com/items)在浏览器中获得准确的结果。

已更新 这是我的 Vue routes.js 文件

import Example from './components/ExampleComponent.vue'
import CreateItem from './components/CreateItem.vue'
import DisplayItem from './components/DisplayItem.vue'
import EditItem from './components/EditItem.vue'

export const routes = [
    { name: 'Example', path: '/', component: Example },
    { name: 'CreateItem', path: '/items/create', component: CreateItem },
    { name: 'DisplayItem', path: '/items', component: DisplayItem },
    { name: 'EditItem', path: '/items/:id/edit', component: EditItem }
];

像这样从 Laravel 获得响应

$items = Items::all();
//        dd($items);
        return response()->json($items);

DisplayItems.vue 文件 Vue.js 代码

<script>
    export default {
        data(){
            return{ items: [] }
        },
        created: function()
        {
            this.fetchItems();
        },
        methods: {
            fetchItems()
            {
                this.axios.get('/items').
                    then(response => {
                        this.items = response.data;
                    });
            },
            deleteItem(id)
            {
                let uri = '/items/'+id;
                this.items.splice(id, 1);
                this.axios.delete(uri);
            }
        }
    }
</script>

【问题讨论】:

    标签: laravel laravel-5 vue.js vuejs2 vue-component


    【解决方案1】:

    Laravel 从路由 /items 返回一个 JsonResponse,这就是为什么你会在浏览器中看到 JSON。 Vue 将 JSON 绑定到 dom 元素。

    您需要修改到 /items 的路由,以便它在 $request-&gt;wantsJson() 时返回 JSON,如果不是 ajax,则返回常规响应。

    【讨论】:

    • 等我给你看我的 Vue 路由文件
    • 请再次检查文件源代码
    • Vue 路由用于客户端路由,它们不发出 api 请求,axios 是。您必须有一个 routes.php 文件或类似文件,是吗?里面是Route::get('items', 'ItemController')?就像我说的,你需要修改服务器端函数,以便在使用浏览器访问时返回视图响应和项目数据。
    • 如何添加服务器端功能?我的控制器代码已经在上面添加了。我怎样才能重新渲染vue?请在这里写一个简单的例子
    • app/Http/Controllers 中是否有 ItemController?
    【解决方案2】:

    [BEHAVIOUR]
    laravel 拥有自己的带有路由的服务器。 当您尝试刷新自定义 Vue.js 路由时,它会显示用 laravel 路由覆盖 Vue.js 路由,并且只显示 JSON 响应。
    [解决方案]
    您应该创建Vue.js 应用程序并使用laravel-echolaravel broadcasting 并使用laravel api。
    现在从 Vue 发出每个请求以直接 API 并获取响应。

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2020-01-19
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多