Laravel中使用Vue與VueRoute
現在不管在台灣還是在日本,使用 Laravel 框架的人相當的多,我從事碼農工作四年多以來,Codeigniter用了三年多(剩下一年都在寫Java),雖然我很愛Codeigniter,不是很想放棄使用它。但是為了糊口飯吃,還是得學習一下熱門的框架怎麼用(泣)
因為我現在前端也用蠻多的,而且熱衷寫 Vue.js 所以紀錄一下怎麼在 Laravel 裡用 vue.js
安裝Laravel
composer global require "laravel/installer"
laravel new hello-laravel
安裝 npm 套件
cd hello-laravel
composer install
安裝 vue 與 vue-route
npm install vue vue-router --save-dev
新增 App/Http/Controllers/HelloController.php
<?php
namespace App\Http\Controllers;
class HelloController extends Controller
{
public function index()
{
return view('hello');
}
}
新增 resources/views/hello.blade.php
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-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>My Apps</title>
<link rel="stylesheet" type="text/css" href="/css/app.css">
</head>
<body>
<div id="app">
<router-link to="/home">Home</router-link>
<router-link to="/about">about</router-link>
<router-view></router-view>
</div>
<script src="/js/app.js"></script>
</body>
</html>
新增 resources/js/components/Home.vue
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Home Page</div>
<div class="panel-body">I'm Home Page!</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {};
</script>
新增 resources/js/components/About.vue
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">About Page</div>
<div class="panel-body">I'm About Page!</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {};
</script>
修改路由 routes/web.php
Route::get('/{any}', 'HelloController@index')->where('any','.*');
修改 resources/js/app.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './components/Home';
import About from './components/About';
window.Vue = Vue;
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/photo-app/photo-app/public/home',
name: 'home',
component: Home
},
{
path: '/photo-app/photo-app/public/about',
name: 'about',
component: About,
},
],
});
const app = new Vue({
el: '#app',
router,
});
確認一下 webpack.mix.js 是否為以下代碼
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
以上都確認完畢後,我們就可以開始把各個 js 文件與 vue 文件都打包到 public/js 裡面
成為單一的 js 文件
打包
npm run dev
啟動伺服器(使用apache或是nginx的可以略過)
php artisan serve
接著訪問 http://localhost 或 http://127.0.0.1:8000 應該就能看到結果了
參考: