简体   繁体   English

Laravel刀片模板更改为Vue组件

[英]Laravel blade template changing to vue component

So I just recently finished my project using only laravel framework. 因此,我最近仅使用laravel框架完成了我的项目。 Now that I've finished working on it, I want to add vue.js into my project by making the content refresh without refreshing the layout page. 现在,我已经完成了工作,我想通过刷新内容而不刷新布局页面来将vue.js添加到我的项目中。 And also I want to convert my blade files into vue components. 我也想将刀片文件转换为vue组件。 And I don't know how to do it because in every section in my project, I have 4 blade files like index,edit,create,show and I don't know how to do make that in the component and it is difficult to me because I'm using laravel collective form that's why it refreshes every-time I add some entry into the database. 而且我不知道该怎么做,因为在我项目的每个部分中,我都有4个刀片文件,如index,edit,create,show,而且我不知道如何在组件中做到这一点,因此很难我,因为我使用的是laravel集体形式,这就是为什么每次我在数据库中添加一些条目时都会刷新的原因。 Im also new to vuejs. 我也是vuejs的新手。 Can someone help me out of this? 有人可以帮我吗? Thanks a lot. 非常感谢。

My folder directory is like this. 我的文件夹目录是这样的。

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

Here are some of my codes. 这是我的一些代码。

roadmap/index.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 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 web.php

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

there are many different ways to have vue components in our laravel application. 在我们的laravel应用程序中,有很多不同的方式来拥有vue components Basic idea is to execute SPA (Single Page Application), I'll tell you how I do it. 基本思想是执行SPA(单页应用程序),我将告诉您如何执行。

Laravel provides basic entry point for our vuejs application. Laravel为我们的vuejs应用程序提供了基本的入口点。 You can see in your webpack.mix.js file. 您可以在webpack.mix.js文件中看到。 For the routes I use vue-router and rest api for CRUD operation. 对于路由,我使用vue-routerrest api进行CRUD操作。 So you need to do following setup: 因此,您需要执行以下设置:

npm install
npm install vue-router --save

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

In your case I would make a single blade file which will act as entry point for Vue application. 在您的情况下,我将制作一个刀片文件,该文件将用作Vue应用程序的入口点。 I would define in route web.php 我会在路线web.php定义

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

In HomeController I'll simply return the blade view HomeController我将简单地返回刀片视图

return view('landing')

Now in will make landing.blade.php : 现在将使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>

You have to mention csrf_token() in the meta tag and a div with id so that it can render vue-components over there. 您必须在meta标记中提及csrf_token()和一个iddiv ,以便它可以在那儿渲染vue-components

Now I'll create a router file for vuejs will create router.js in resources folder: 现在,我将为vuejs创建一个router文件,将在resources文件夹中创建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: '/',
});

Rest you can do for Create , Update forms. 其余的您可以为CreateUpdate表单做。 Now we will configure our app.js file present inside resource folder: 现在,我们将配置存在于资源文件夹中的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)
});

Then I'll create welcome component which will act as entry point for vue-router , will create a welcome.vue file: 然后,我将创建welcome组件,该组件将用作vue-router入口点,将创建一个welcome.vue文件:

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

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

<style lang="scss">


</style>

Now I'll make API's for CRUD operation: 现在,我将为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;;
    }

}

I would then make api in api.php 然后我将在api.php制作api

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

Now only thing left out is calling these api in our component file and executing as per our requirement. 现在唯一剩下的就是在我们的组件文件中调用这些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>

I hope you get a basic idea to execute things on your own. 我希望您有一个基本的想法可以自己执行事情。 There are lot of tutorials which can be found: 有很多教程可以找到:

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

Hope this helps. 希望这可以帮助。 Cheers. 干杯。

PS: You have to keep compiling via npm run dev or npm run watch after you finish coding vue-component . PS:完成对vue-component编码后,您必须继续通过npm run devnpm run watch进行编译。 Code may not work or might have bugs. 代码可能不起作用或存在错误。 This is only to give you direction to start through. 这只是给您指导的方向。

Don't know if its help you or not , but i am sharing my thoughts. 不知道它是否对您有帮助,但是我正在分享我的想法。

  1. add js file in laravel webpack 在laravel webpack中添加js文件
  2. in js file add your component 在js文件中添加您的组件
  3. in component add your code for @foreach you can use v-for="data in roadmap" 在组件中为@foreach添加代码,您可以在路线图中使用v-for =“ data”

     <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. for controller index function: 对于控制器索引功能:

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

let me know if their any lack of understanding. 让我知道他们是否缺乏理解。 i will update my answer 我将更新我的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM