Tạo ứng dụng Laravel 5.4 kết hợp với Vuejs

Tình hình là Vuejs đang lấy ưu thế hơn Angular và React, mình cũng đã tìm hiểu qua Angular 2 mình thấy là Vuejs thấy code nhẹ hơn so với Angular 2 không cần include nhiều thư viện vào giống như Angular 2, Còn React thì mình chi xem qua sơ thôi chưa có làm Demo để xác nhận như thế nào, Ban đầu mình mê code Angular V2 lắm sao đó thấy việc tích hợp vào Laravel thì nó hơi căng hơn so với Vuejs nên mình dùng Vuejs xem sao, và theo cảm nhận của mình thì ok êm, còn mấy bạn thì mình không biết hehe

Nay mình xin hướng dẫn các bạn về Vuejs kết hợp với Laravel 5.4, sử dụng Axios để get API nhé mấy bạn, khá thú vị, mình đã làm rồi và mong được chia sẽ cùng mọi người kinh nghiệm nhỏ nhỏ này!



Đầu tiên các bạn chuẩn bị cài đặt laravel 5.4 và thư viện Vuejs theo mình như sau
Bước 1:Cài Laravel 5.4
 câu lệnh sau:
 composer create-project --prefer-dist laravel/laravel blog "5.4.*"
Bước 2:Sau khi cài đặt bạn cần gỏ câu lệnh: npm install để tải các thư viện của laravel về các bạn có thể mở file package.json để xem
Bước 3:Các bạn chạy lệnh sau:
* cài đặt câu lệnh bên dưới cho VueJS để tích hợp vào thư viện
 npm install --save-dev vue-axios vue-loader vue-router vue-template-compiler

Vậy là xong các bước để để tích hợp Vuejs vào laravel 5.4, các bạn sẽ nhìn thấy trong thư mục project của bạn có một thư mục là node_modules là bộ thư viện mình vừa cài đặt các câu lệnh bên trên

Giờ chúng ta thử chạy project trên bạn chạy câu lệnh như sau:
npm run dev
php artisan serve

Tiếp theo
* Cấu hình database và tạo table thì mình không cần nói tới nửa chắc các bạn cũng đã biết hết rồi nhé
 - tạo controller: SanphamController
   php artisan make:controller PhotoController --resource
   
 - tạo model: Sanphams.php
   php artisan make:model Sanphams
   
* Ở đây mình có database:demo, table:sanphams được tạo trong xampp của mình rồi! còn lại các bạn tự cấu hình kết nối đến database của bạn là được!

* Giờ chúng ta làm việc với Vuejs thôi nào
- Bạn vào sửa lại file welcome.blade.php này như sau:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta https-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel Vue CRUD Application</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="app">
        </div>
         <script>
           window.Laravel = <?php echo json_encode([
               'csrfToken' => csrf_token(),
                    ]); ?>
          </script>
        <script src="{{asset('js/app.js')}}"></script>
    </body>
</html>

- Tiếp theo vào đường dẫn C:\xampp\htdocs\laravel-vuejs\resources\assets\js\components và tạo các file như sau
 + Listsp.vue, CreateSanpham.vue, EditSanpham.vue
 các bạn copy các code bên dưới vô đúng từng file nhé
 *Listsp.vue: dùng hiển thị các sản phẩm ra

<template>
	 <div class="container">
		<h1 class="label label-danger">Danh sách sản phẩm</h1>
		 <router-link :to="{ name: 'CreateSanpham' }" class="label label-primary">Create Item</router-link>
		<div class="row">
			<div class="col-md-12">
				<table class="table">
					<thead>
						<tr>
							<th>STT</th>
							<th>Tên SP</th>
							<th>Gía SP</th>
							<th>Sửa</th>
							<th>Xóa</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(sanpham, index) in sanphams">
							<td>{{index+1}}</td>
							<td>{{sanpham.name}}</td>
							<td>{{sanpham.price}}</td>
							<td><router-link :to="{name:'EditSanpham',params:{ id:sanpham.id }}" class="label label-warning">Sửa</router-link></td>
							<td><a href="#" v-on:click="DeleteSanpham(sanpham.id)" class="label label-danger">Xóa</a></td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</template>
<script>
    export default {
       data(){
            return{
                sanphams: []
            }
        },
       created: function()
        {
            this.fetchItems();
        },
       methods:{
       	   fetchItems(){
       	   		this.axios.get("https://localhost:8000/sanpham").then((response)=>{
       	   			this.sanphams = response.data;
       	   			console.log(response.data);
       	   		});
       	   },
       	   DeleteSanpham(id){
       	   	 let uri = `https://localhost:8000/sanpham/${id}`;
              this.sanphams.splice(id, 1);
              this.axios.delete(uri);
       	   }
       }
    }
</script>

* CreateSanpham.vue: Dùng tạo sản phẩm mới

<template>
	<div class="container">
		<h1 class="label label-danger">Thêm sản phẩm</h1>
		<h5 class="label label-success" v-if="check">Thêm thành công!</h5>
		
		<div class="row">
			<div class="col-md-12">
				<table class="table">
					<tbody>
						<tr>
							<td>Tên sản phẩm</td>
							<td><input type="text" name="tensp" class="form-control" placeholder="Nhập tên sản phẩm" v-model="sanpham.tensp" /></td>

						</tr>
						<tr>
							<td>Giá sản phẩm</td>
							<td><input type="int" name="giasp" class="form-control" placeholder="Nhập giá sản phẩm" v-model="sanpham.giasp" /></td>
						</tr>
						<tr>
							<td colspan="2">
								<button class="btn btn-info" v-on:click="addsp">Thêm</button>
							</td>
						</tr>
					</tbody>
				</table>
			</div>	
		</div>
	
	</div>
</template>
<script>
	export default{
		data(){
			return{
	          sanpham:{},
	          check:false
	        }
		},
		methods:{
			addsp:function(){
				this.axios.post("https://localhost:8000/sanpham",this.sanpham).then((response)=>{
					//this.check=true;
					this.$router.push({name: 'Listsp'})
					console.log("them thanh cong");
				});
			}
		}
	}


</script>

* EditSanpham.vue : Dùng edit sản phẩm

<template>
	<div class="container">
		<h1 class="label label-danger">Edit sản phẩm</h1>
		<h5 class="label label-success" v-if="check">Edit thành công!</h5>
		<router-link :to="{ name: 'Listsp' }" class="label label-warning">Back Danh sách SP</router-link>
		<div class="row">
			<div class="col-md-12">
				<table class="table">
					<tbody>
						<tr>
							<td>Tên sản phẩm</td>
							<td><input type="text" name="tensp" class="form-control" placeholder="Nhập tên sản phẩm" v-model="sanpham.name" /></td>

						</tr>
						<tr>
							<td>Giá sản phẩm</td>
							<td><input type="int" name="giasp" class="form-control" placeholder="Nhập giá sản phẩm" v-model="sanpham.price" /></td>
						</tr>
						<tr>
							<td colspan="2">
								<button class="btn btn-info" v-on:click="editsp">Cập nhật</button>
							</td>
						</tr>
					</tbody>
				</table>
			</div>	
		</div>
	
	</div>
</template>
<script>
	export default{
		data(){
			return{
	          sanpham:[],
	          check:false
	        }
		},
		created: function(){
            this.getItem();
        },
		methods:{
			getItem()
            {
              let uri = `https://localhost:8000/sanpham/${this.$route.params.id}/edit`;
                this.axios.get(uri).then((response) => {
                    this.sanpham = response.data;
                });
            },
			editsp:function(){
				this.axios.patch('https://localhost:8000/sanpham/'+this.$route.params.id,this.sanpham).then((response)=>{
					this.check=true;
					console.log("Edit thanh cong");
				});
			}
		}
	}


</script>

- Tiếp theo các bạn đường dẫn như sau C:\xampp\htdocs\laravel-vuejs\resources\assets\js 
 * tạo file App.vue: dùng đẻ đưa nội dung từ template tạo bên trên vào chổ <router-view></router-view>

<template>
    <div class="container">
        <div>
            <transition name="fade">
                <router-view></router-view>
            </transition>
        </div>
    </div>
</template>

<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>

<script>

    export default{
    }

- Tiếp theo bạn mở file app.js cũng nằm trong đường dẫn trên, sửa lại thành code bên dưới như sau:

import Vue from 'Vue';

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';//gọi thư viện axios
import axios from 'axios';
Vue.use(VueAxios,axios);


import App from './App.vue';
//incldue listsp
import ListSP from './components/Listsp.vue';

//includde createsanpham
import CreateSanpham from './components/CreateSanpham.vue';
//incldue editsanpham
import EditSanpham from './components/EditSanpham.vue';

const routes = [
  {
      name: 'Listsp',
      path: '/',
      component: ListSP
  },
  {
  	name:'CreateSanpham',
  	path:'/sanpham/create',
  	component:CreateSanpham
  },
  {
    name:'EditSanpham',
    path:'/sanpham/edit/:id',
    component:EditSanpham
  }

];

const router = new VueRouter({mode:'history', routes: routes});
new Vue(Vue.util.extend({router},App)).$mount('#app');

- file app.js dùng để cầu hình gọi các thư viện và template, và khởi tạo các router điều hướng trên địa chỉ

- Tiếp theo các bạn mởi web.php lên chỉnh sửa lại router như sau:

Route::get('/', function () {
    return view('welcome');
});

Route::resource('sanpham', 'SanphamController');

Giớ tới các bước chúng ta muốn lấy dữ liệu ra và trả về cho Vuejs để hiển thị lên template ta làm như sao. Dữ liểu trả về là json nhé các bạn

Các bạn mở file SanphamController.php và sửa lại như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Sanphams;
class SanphamController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         $items = Sanphams::all();
        return response()->json($items);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $sanpham = new Sanphams;
        $sanpham->name=$request->tensp;
        $sanpham->price=$request->giasp;
        $sanpham->save();
     
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {   
       
       
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $sanpham = Sanphams::find($id);
        return response()->json($sanpham);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $sanpham = Sanphams::find($id);
        $sanpham->name = $request->get('name');
        $sanpham->price = $request->get('price');
        $sanpham->save();
        return response()->json('Successfully Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
         $sanpham = Sanphams::find($id);
         $sanpham->delete();

       return response()->json('Successfully Deleted');
    }


}
?>

Mình đã đi sơ qua các bước để kết hợp giữa Laravel + Vuejs, các bạn có thể làm giống mình để tìm hiểu một chút đôi nét về ngôn ngữ Vuejs này như thế nào, Theo mình cảm nhận thì Vuejs dễ dùng, nhưng còn tùy thuộc vào mấy bạn có cảm nhận thế nào! Chúc các bạn làm thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)