【问题标题】:Laravel blade template changing to vue componentLaravel 刀片模板更改为 vue 组件
【发布时间】:2019-12-02 03:35:34
【问题描述】:

所以我最近只使用 laravel 框架完成了我的项目。现在我已经完成了它的工作,我想通过刷新内容而不刷新布局页面来将 vue.js 添加到我的项目中。而且我想将我的刀片文件转换为 vue 组件。而且我不知道该怎么做,因为在我的项目的每个部分中,我都有 4 个刀片文件,如索引、编辑、创建、显示,我不知道如何在组件中制作它,而且很难我是因为我使用的是 laravel 集体形式,这就是为什么每次我在数据库中添加一些条目时它都会刷新。我也是 vuejs 的新手。有人可以帮我解决这个问题吗?非常感谢。

我的文件夹目录是这样的。

-roadmap
---index.blade.php
---show.blade.php
---edit.blade.php
---create.blade.php

这是我的一些代码。

路线图/index.blade.php

@extends('layouts.admin')




@section('content')

<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- DATA TABLES -->
<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet"href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">


<div><a class="btn btn-success" style="float:right" href="{{ route('roadmap.create') }}">Add Roadmap</a></div>

<table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th scope="col">ID</th>
        <th scope="col">Year Covered </th>
        <th scope="col">Description</th>
        <th scope="col">Date entered</th>



        <th width="280px">Action</th>
      </tr>
    </thead>
    <tbody>
        @foreach ($roadmap as $data)
        <tr>
           <td>{{ $data->id }}</td>
           <td>{{ $data->year}}</td>
           <td>{{ $data->body}}</td>
           <td>{{ $data->created_at}}</td>


        <td>

        <a href="/roadmap/{{$data->id}}/edit" class="btn btn-warning"><span class="glyphicon glyphicon-pencil"></span></a>

        <a href="/roadmap/{{$data->id}}" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span></a>

        {!! Form::open(['method' => 'DELETE', 'route'=>['roadmap.destroy', $data->id], 'style'=> 'display:inline', 'onsubmit' => 'return confirm("Are you sure you want to delete?")']) !!}
        {!! Form::button('<i class="fa fa-trash"></i>',['type'=>'submit', 'class'=> 'btn btn-danger']) !!}
        {!! Form::close() !!}</td>


        </tr>
        @endforeach
    </tbody>
  </table>

  <script>
    $(document).ready(function() {
      $('#myTable').DataTable();

  } );
   </script>




@endsection

RoadmapController.php

<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\Roadmap;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;

class RoadmapController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $roadmap = DB::table('roadmaps')->get();

        return view('roadmap.index', ['roadmap' => $roadmap]);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('roadmap.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        request()->validate([
            'year' =>['required', 'string', 'max:255', 'unique:roadmaps'],
            'body' => ['required', 'string', 'max:255'],
          ]);

          Roadmap::create($request->all());
          return redirect()->route('roadmap.index')->with('success','Created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $roadmap = Roadmap::find($id);
        return view('roadmap.show', compact('roadmap'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $roadmap = Roadmap::find($id);
        return view('roadmap.edit', compact('roadmap'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        request()->validate([
            'year' => 'required',
            'body' => 'required',
          ]);
          Roadmap::find($id)->update($request->all());
          return redirect()->route('roadmap.index')->with('success',' Updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Roadmap::find($id)->delete();
        return redirect()->route('roadmap.index')->with('success','News deleted successfully');
    }

}

web.php

//CRUD COLLECTIVE ROADMAP
    Route::resource('roadmap', 'RoadmapController');

【问题讨论】:

  • 你知道刀片组件的使用方法吗?
  • 我知道一点先生,但我很困惑是否应该在 vue 中创建 4 个组件,如 create、index 等。我只知道如何通过创建 &lt;component-name&gt; 在刀片文件中渲染我的组件和一些小的 CRUD axios。我也很困惑@foreach 是否可以在我的组件中工作,因为我使用控制器中的compact 函数将数据传递给我的视图

标签: javascript php laravel vue.js


【解决方案1】:

在我们的laravel 应用程序中拥有vue components 有多种不同的方式。基本思路是执行SPA(Single Page Application),我会告诉你我是怎么做的。

Laravel 为我们的 vuejs 应用程序提供了基本的入口点。您可以在 webpack.mix.js 文件中看到。对于路线,我使用vue-routerrest api 进行CRUD 操作。所以你需要做以下设置:

npm install
npm install vue-router --save

npm run dev // To compile app.js and store into public folder

在您的情况下,我将制作一个刀片文件,作为Vue 应用程序的入口点。我会在路线中定义web.php

Route::get('/{view?}', 'HomeController@landing')->where('view', '(.*)')->name('landing');

HomeController 我将简单地返回刀片视图

return view('landing')

现在将制作landing.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>welcome.</title>
        <meta name="description" content="Login Page">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <meta name="csrf-token" content="{{ csrf_token() }}">

    </head>
    <body>

        <div id="website">
        </div>

        <script src="{{ mix('js/app.js') }}"></script>

    </body>
</html>

您必须在元标记中提及csrf_token(),并在id 中提及div,以便它可以在那里呈现vue-components

现在我将为vuejs 创建一个router 文件,然后在资源文件夹中创建router.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

export const router = new VueRouter({
    mode: 'history',
    routes:
        [
            {
                path: '/',
                component: Vue.component('welcome', () => import('./components/Welcome.vue')),
                name: 'welcome',
            },
            {
                path: '/roadmap',
                component: Vue.component('roadmap-index', () => import('./components/Roadmap/index.vue')),
                name: 'roadmap.index',
            },

        ],
    base: '/',
});

您可以为CreateUpdate 表单做其他事情。现在我们将配置资源文件夹中的app.js 文件:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

import VueRouter from 'vue-router';
import {router} from "./routes";
import welcome from './components/Welcome';

window.Vue = require('vue');

Vue.use(VueRouter);

const layoutOne = new Vue({
    el: '#website',
    router: router,
    render:h=>h(welcome)
});

然后我将创建welcome 组件作为vue-router 的入口点,将创建一个welcome.vue 文件:

<template>
    <div>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: "welcome",
    }
</script>

<style lang="scss">


</style>

现在我将为 CRUD 操作制作 API:

<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use App\Roadmap;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;

class RoadmapController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $roadmap = DB::table('roadmaps')->get();

        return response()->json(['roadmap' => $roadmap], 200);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        request()->validate([
            'year' =>['required', 'string', 'max:255', 'unique:roadmaps'],
            'body' => ['required', 'string', 'max:255'],
          ]);

          Roadmap::create($request->all());
          return response()->json(['message' => 'Created successfully'], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $roadmap = Roadmap::find($id);
        return response()->json(['roadmap` => $roadmap],200);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        request()->validate([
            'year' => 'required',
            'body' => 'required',
          ]);
          Roadmap::find($id)->update($request->all());
          return response()->json(['message' => 'Updated successfully'], 200;;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Roadmap::find($id)->delete();
        return response()->json(['message' => 'Deleted'], 200;;
    }

}

然后我会在 api.php 中制作 api

Route::resource('roadmap', 'RoadmapController');

现在唯一剩下的就是在我们的组件文件中调用这些 api 并按照我们的要求执行。

<template>
    <table class="table table-hover">
        <thead class="demo">
        <tr>
            <th>Roadmap</th> //Whatever you have headers
            <th>Update</th>
            <th>Delete</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in roadmaps">
            <td>{{ item.name }}</td>  // Whatever your data field is
            <td @click="update(item)">Update</td>
            <td @click="delete(item)"> Delete</td>
        </tr>
    </table>
</template>

<script>
    export default {
        data() {
            return: {
                roadmaps: [],
                errors: ''
            }
        },
        methods: {
            fetchData() {
                axios.get('api/roadmap).then(response => {
                    if(response.status === 200)
                    {
                        this.roadmaps = response.data
                    }
                }).catch((error) => {
                    this.errors = error.response.data
                })
            },
            update(item) {
                this.$router.push({ name: update, params: { id: item.id}})
            },
            delete(item) {
                axios.delete('api/roadmap/'+item.id).then(response => {
                    if(response.status === 200)
                    {
                        this.fetchData()  // to refresh table..
                    }
                }).catch((error) => {
                    this.errors = error.response.data
                })
            }
        }
        created() {
            this.fetchData()
        }
    }
</script>

我希望你有一个基本的想法来自己执行一些事情。有很多教程可以找到:

https://laravel-news.com/using-vue-router-laravel

希望这会有所帮助。干杯。

PS: 完成vue-component 编码后,您必须通过npm run devnpm run watch 继续编译。代码可能不起作用或可能有错误。这只是为您提供指导。

【讨论】:

  • 非常感谢先生的回答。我会先尝试理解它,然后我会将它应用到我的代码中。
  • 先生,我有一个问题,为什么我需要使用api.php 路由?我无法将我的路线用于我的 web.php 中的资源
  • 是的,你可以,但是如果你检查你的app\http\kernel.php,有很多中间件对 REST API 很有帮助,而我们的web.php 中间件中没有提到。
  • 好的,先生。但是我有这件事困扰着我,我应该在哪里创建视图以进行创建、显示等..?我是否必须为此制作另一个组件,例如show.blade.vue?或者可能会制作一个模态并将代码插入我的 vue 组件中?
  • 我第一次知道它有点难以理解。这就是为什么我告诉你有很多教程可用。只需使用 Laravel 和 Vuejs 搜索单页应用程序 (SPA)。你会得到很多东西来消除你所有的疑惑。
【解决方案2】:

不知道对你有没有帮助,但我正在分享我的想法。

  1. 在 laravel webpack 中添加 js 文件
  2. 在 js 文件中添加你的组件
  3. 在组件中添加您的代码 对于@foreach,您可以使用 v-for="data in roadmap"

    <tr v-for="data in roadmap">
       <td> {{ data.id }}</td>
       <td> {{ data.year }}</td>
    <td>
    <a :href="'/roadmap/'+ data.id +'/edit'" class="btn btn-warning">
     <span class="glyphicon glyphicon-pencil"></span>
    </a>
    </td>
    </tr>
    
  4. 控制器索引功能:

        if($request->ajax()){
            $roadmap = DB::table('roadmaps')->get();
            return response()->json($roadmap, 200);
        }
    
        return view('roadmap.index');
    
  5. 要提交表单,您可以在点击按钮上添加方法。

如果他们缺乏理解,请告诉我。我会更新我的答案

【讨论】:

  • 感谢 los 先生的回答。我会尝试理解它,然后我会在我的项目中尝试它。
猜你喜欢
  • 2018-09-24
  • 2021-11-27
  • 1970-01-01
  • 2016-03-18
  • 2020-06-22
  • 2020-06-24
  • 2013-04-29
  • 2018-12-08
相关资源
最近更新 更多