Laravel 5.7 + Vue SPA

Cũng khá lâu rồi mình không viết bài chia sẻ kiến thức nào, nay mình chia sẻ với mấy bạn cách tạo SPA bằng sự kết hợp giữa Laravel 5.7 + Vue

Đầu tiên các bạn cần cài đặt project laravel 5.7 bằng câu lệnh như sau:
+ Install project laravel 5.7
  # composer globar require "laravel/installer"
  # laravel new laravel57-vuejs
  # npm install 

+ Install (Vue,Vue-router,vue-loader,vue-template-compiler)
  # npm install vue vue-router vue-loader vue-template-compiler

Sau khi cài đặt bạn sẽ thấy package.json của bạn như sau:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^2.0",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "vue": "^2.5.17",
        "vue-loader": "^14.2.3",
        "vue-template-compiler": "^2.5.17"
    },
    "dependencies": {
        "vue-router": "^3.0.1"
    }
}

Khi chạy câu lệnh cài đặt vue và vue-router bạn sẽ thấy một thư mục node_modules được tạo ra trong project laravel57-vuejs của mình

Tiếp theo bạn cần tạo một template root để chúng ta có thể load các component vue ra template, bạn tạo cho mình thư mục layouts trong resources/views/layouts/main.blade.php các bạn chú ý tới id="app" là nơi chúng ta render các component ra.

File main.blade.php

<!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">
			<meta name="csrf-token" content="{{ csrf_token() }}">
			<title>Laravel Vuejs</title>
			<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		   
		  <link rel="stylesheet" type="text/css" href="{{asset('css/styles.css')}}">
		</head>
		<body>
			<section id="app" class="container">
				  
			</section>
		</body>
		<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
	</html>

Chúng ta thường biết là laravel dùng back-end, còn vue.js chúng ta sẽ làm front-end, trong vue.js chúng ta có router để tạo các định tuyến chuyển trang, còn trong laravel chúng ta thiết lập router để xây dựng back-end. giờ chúng ta vào thư mục routes/web.php chúng ta sửa lại Router như sau:

Route::get('/{any}', 'SinglePageController@index')->where('any', '.*');

Nếu không có đoạn Router trên  thì bộ định tuyến router trong vue.js sẽ không hoạt động nhé!

Giờ thì ta cần tạo Controller file "SinglePageController" trong file controller này các có thể viết các hàm xử lý dữ liệu các bạn muốn!
 # php artisan make:controller SinglePageController --resource 
Bạn sẽ nhìn thấy file vừa tạo trong đường dẫn app/Http/Controllers/, tiếp bạn mở file SinglePageController và sửa lại hàm index() như sau:
 

public function index() {
    return view('layouts/main'); //chỉ đến thư mục layouts chứ file main.blade.php 
}

Giờ ta cần mở file app.js trong thư mục resources/js/app.js lên cấu hình nó, file app.js dùng cấu hình import các component và routes, thư viện vào để dùng chúng.

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

import Home from './components/Home.vue';
import About from './components/About.vue';
import App from './App.vue';


const router = new VueRouter({
	mode:'history',
	routes:[
		{
			path:'/',
			name:'Home',
			component:Home
		},
		{
			path:'/about',
			name:'About',
			component:About
		}
	
	]
});

const app = new Vue({
	el:'#app',
	router:router,
	render:h=>h(App),
});
export default app;

Ở bên trên mình import các file component vào các bạn có thể nhìn thấy đoạn code bên trên,giờ ta chỉ cần tạo các component như trên là được
* App.vue(component ta thiết lập <router-view></router-view> để các component khác nó render template ra tại đây)

<template>
    <div class="box-template">
        <ul>
            <li><router-link :to="{name:'Home'}">Home</router-link></li>
            <li><router-link :to="{name:'About'}">About</router-link></li>
        </ul>
        <router-view></router-view>
    </div>
</template>
<script>
    export default {
        
    }

</script>

* (Home.vue,About.vue) (template giao diện trang chủ các bạn code sao cũng được)

<template>
    <div class="box-home">
        <h2>Component Home</h2>
    </div>
</template>
<script>
    export default {
        
    }

</script>

* About.vue

<template>
    <div class="box-home">
        <h2>Component About</h2>
    </div>
</template>
<script>
    export default {
        
    }

</script>

Sau khi ta tạo các component xong để chạy được project bạn tiến hành mở 2 cái cmd và chạy 2 câu lệnh dưới đây

* Cmd 1: # npm run watch

* Cmd 2: # php artisan serve

Sau đó bạn gõ trên trình duyệt http://127.0.0.1:8000 để thấy thành quả của mình nhé! ::)

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!)