当前Laravel版本:6.18.3
当前Vue版本:2.6.11
确保在此之前已经安装好composer、node,如果需要sass,还要有python运行环境
一、创建Laravel项目:
composer create-project --prefer-dist laravel/laravel demo "6.*"
1、配置package.json中的依赖项:
package.json:
"devDependencies": {
"cross-env": "^7.0",
"laravel-mix": "^5.0.1",
"lodash": "^4.17.13",
"resolve-url-loader": "^3.1.0",
"vue-template-compiler": "^2.6.11"
},
"dependencies": {
"axios": "^0.19.2",
"vue": "^2.6.11",
"vue-router": "^3.1.6",
"vuex": "^3.1.3"
}
2、sass选项
如果不使用sass,先将resources/sass/app.scss改名为resources/css/app.css,然后设置webpack.mix.js,需要sass的飘过本小2:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.copy('resources/css/*.css', 'public/css');
3、安装依赖项:
npm install
如果以后需要sass,再安装以下依赖项:
npm i -D node-sass fibers sass sass-loader
注:在安装node-sass时会自动从github下载.node文件(此文件依赖python),可能会比较慢,建议更换国内源。
二、引入Vue:
1、修改路由
在routers/web.php路由文件中修改路由项,定位到index:
Route::get('/', function () {
return view('index');
});
2、新建vue模板文件
新建resources/components/Hello.vue文件:
<template>
<div>
<h1>Hello, Laravue!</h1>
<p class="msg">{{ msg }}</p>
</div>
</template><script>
export default {
data() {
return { msg: 'This is a Laravel 6.x with Vue project.' }
}
}
</script><style>
h1 { text-align: center; }
.msg { font-size: 16px; color: green; text-align: center; }
</style>
3、创建Vue实例并渲染
在resources/js/app.js文件中创建Vue实例,引入模板文件并渲染:
require('./bootstrap');
window.Vue = require('vue');import Hello from '../components/Hello';
const app = new Vue({
el: '#app',
render: h => h(Hello)
});
4、新建blade视图文件关联vue
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravue</title>
</head>
<body>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
5、打包运行
npm run dev
npm run watch
看到这样就算是成功将啦!