轉載自https://blog.csdn.net/qq_21859119/article/details/82843795
源碼
1、安裝node環境
具體安裝教程請參考http://nodejs.cn/
2、塔建Vue前端項目
使用Vue官網提供的vue-cli腳手架vue-cli命令行工具
# 全局安裝 vue-cli
$ npm install --global vue-cli
# 創建一個基於 webpack 模板的新項目
$ vue init webpack nevem
# 安裝依賴,走你
$ cd nevem
$ npm install
$ npm run dev
注意:
npm install --global vue-cli
全局安裝 vue-cli。
vue init webpack nevem
創建一個基於 webpack 模板的新項目。在這一步時,下圖的這幾個單元測試和代碼檢驗工具建議填寫no,不然會增加項目的體積和寫代碼時因爲不規範產生一大堆報錯。
cd nevem
安裝vue-resource和element-ui依賴: cd nevem進入前端項目後,找到package.json文件對應的地方,確保有添加如下代碼:
"dependencies": {
"element-ui": "^1.3.2",
"vue": "^2.2.6",
"vue-resource": "^1.0.3",
"vue-router": "^2.3.1"
},
npm install
安裝所有的依賴,包括上一步驟的elementUI和vue-resource。
執行npm install安裝時間會長一點,所以建議使用淘寶cnpm鏡像(自行google),公司的網絡已牆的請忽略。
npm run dev後頁面自動彈出http://localhost:8080/#/這個頁面,表明基於webpack的vue項目成功創建。
3、引入Element組件
修改src/main.js爲如下代碼,引入element和resource
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
render:h => h(App)
})
修改src/componentsHello.vue文件爲如下代碼,調整首頁的內容
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>{{el}}</p>
<form>
<el-input v-model="name" placeholder="名稱" style="width:200px"></el-input>
<el-input v-model="price" placeholder="價格" style="width:200px"></el-input>
<el-button type="primary" @click="addUser">提交</el-button>
</form>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App',
name: '',
price: '',
el:''
}
},
methods: {
addUser() {
var name = this.name;
var price = this.price;
this.$http.post('/api/user/addUser', {
name: name,
price: price
},{}).then((response) => {
console.log(response);
})
},
aaa(){
this.el="成功引入element";
}
}
}
</script>
保存以上文件之後,在nevem目錄再次運行npm run dev,頁面變成如下效果,則表示成功引入element組件。
4、安裝Mysql
安裝mysql的形式有很多種,這裏我使用的是WampServer建立一個數據庫,具體如果安裝和使用,依舊自行google。
這裏我新增了一個Database數據庫,名稱爲mbvr_live,然後在數據庫裏創建一張表goods並插入了兩條記錄,具體sql代碼如下:
CREATE TABLE IF NOT EXISTS `goods` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`price` float(10,2) NOT NULL,
`creat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `goods` (`id`, `name`, `price`, `creat_time`) VALUES
(1, 'apple', 5.00, '2017-05-11 00:22:10'),
(2, 'banner', 5.00, '2017-05-11 01:37:37');
5、安裝Express
在目錄nevem下新建一個文件service,用於做服務器。在裏面創建如下4個文件,結構如下:
db.js,用來配置mysql連接數據:
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '',
database:'mbvr_live'
}
}
app.js,Express服務器入口文件:
// node 後端服務器入口
const userApi = require('./api/userApi');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//註冊api路由
app.use('/api/user', userApi);
// 監聽端口
app.listen(3000);
console.log('success listen at port:3000......');
sqlMap.js,SQL語句映射文件,以供api邏輯調用:
// sql語句
var sqlMap = {
// 用戶
user: {
add: 'insert into goods(id, name, price) values (0, ?, ?)'
}
}
module.exports = sqlMap;
userApi.js,測試示例:
var models = require('../db/db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../db/sqlMap');
// 連接數據庫
var conn = mysql.createConnection(models.mysql);
conn.connect();
var jsonWrite = function(res, ret) {
if(typeof ret === 'undefined') {
res.json({
code: '1',
msg: '操作失敗'
});
} else {
res.json(ret);
}
};
// 增加用戶接口
router.post('/addUser', (req, res) => {
var sql = $sql.user.add;
var params = req.body;
console.log(params);
conn.query(sql, [params.name, params.price], function(err, result) {
if (err) {
console.log(err);
}
if (result) {
jsonWrite(res, result);
}
})
});
// 增加用戶接口
router.get('/addUser', (req, res) => {
res.send('retrunJson');
});
module.exports = router;
編寫完成之後,就可以在service項目下安裝相關的依賴npm install express mysql body-parser;
此時在service文件夾下執行node app如看到success listen at port:3000,即服務端啓動成功。
6、測試
這時候,返回http://localhost:8080/#/頁面輸入名稱和價格後並提交,發現報http://localhost:8080/api/use… 的404錯誤,這是因爲後端8080和前端3000是兩個不同的端口,跨域了。這時候,找到文件configindex.js,在開發配置dev裏面的地址映射表proxyTable內容爲空,這裏修改爲:
proxyTable: {
'/api': {
target: 'http://127.0.0.1:3000/api/',//不要寫localhost
changeOrigin: true,//true允許跨域
pathRewrite: {
'^/api': '' //需要rewrite重寫的, 如果在服務器端做了處理則可以不要這段
}
}
},