参考源码地址:https://gitee.com/xiaoqiang001/online-retailers
知识点:
Vue、Vuex、Koa2、WebSocket
一、Koa2
koa2是继express之后,node的又一个主流的web框架,相比于express,koa只保留了核心的中间件处理逻辑,去掉了路由、模版以及一些其他的功能,是一个基于node实现的web框架,它所有的功能都是通过插件的形式来实现的。
安装koa
npm init -y
npm install koa
编写app.js
// 1、创建koa对象
const Koa = require('koa')
const app = new Koa()
// 2、编写响应函数(中间件)
// ctx:上下文,web容器,ctx.request ctx.response
// next:下一个中间件,下一层中间件是否能够得到执行,取决于next这个函数有没有被调用
//注意:这里的next函数得到的是Promise对象,拿到对象里面的内容需要用async和await
app.use(async(ctx,next) => {
console.log("第一层中间件")
ctx.response.body = 'hello world'
await next()
})
app.use(async(ctx,next) => {
console.log("第二层中间件")
await next()
})
app.use(async(ctx,next) => {
console.log("第三层中间件")
})
// 3、绑定端口号,node.js里面有
app.listen(3000)
//终端输出
第一层中间件
第二层中间件
第三层中间件
//浏览器输出
hello world
启动服务器
node app.js
二、后台开始
1、计算服务器消耗时长的中间件
module.exports > exports
module.exports对象是由模块系统创建的,自己写模块,需要在模块最后写好模块接口,
声明这个模块对外暴露什么内容,module.exports 提供了暴露接口的方法。
// 计算服务器消耗时长的中间件
// 该中间件必须是第一层,因为要计算服务器消耗时长
module.exports = async (ctx, next) => {
/*
1、记录开始时间
2、内层中间件执行完
3、记录结束时间
4、ctx.set设置响应头 X-Response-Time
*/
const start = Date.now()
await next()
const end = Date.now()
let duration = end - start
ctx.set('X-Response-Time', duration + 'ms')
}
2、用来设置响应头的中间件
// 用来设置响应头的中间件
module.exports = async (ctx, next) => {
//告诉浏览器,给它的是json格式的字符串,编码是UTF-8
const contentType = 'application/json; charset=UTF-8'
ctx.set('Content-Type', contentType)
//ctx.response.body = '{"success": true}'
// 允许跨域
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE')
await next()
}
3、处理业务逻辑的中间件,读取某个json文件并返回
// 处理业务逻辑的中间件,读取某个json文件并返回
const fs = require('fs')
const path = require('path')
const {
getFileJsonData
} = require('../utils/file_utils')
module.exports = async (ctx, next) => {
const url = ctx.request.url
let filePath = url.replace('/api', '')
filePath = `../data/${
filePath}.json`
let fullPath = path.join(__dirname, filePath) // 保证动态的绝对路径
// 保证后台不崩溃,就需要用try-catch
try {
let data = await getFileJsonData(fullPath)
ctx.response.body = data
} catch (error) {
// ctx.response.body = {
// message: '文件不存在'
// }
const errorMsg = {
message: '读取文件内容失败,文件资源不存在',
status: 404
}
ctx.response.body = JSON.stringify(errorMsg)
}
await next()
}
…/utils/file_utils.js
// 读取文件的工具
const fs = require('fs')
module.exports.getFileJsonData = (fullPath) => {
// 异步任务需要通过promise拿到数据,无法直接返回fs.readFile结果的
return new Promise((resolve, reject) => {
fs.readFile(fullPath, 'UTF-8', (err, data) => {
if (err) {
reject('文件不存在')
} else {
resolve(data)
}
})
})
}
三、前端开始
1、devServer对默认服务器端口号进行修改
module.exports = {
devServer: {
port: 3000, //端口号配置
open: true, //自动打开浏览器
}
}
2、echarts.js使用
1、在index.html里面引入echarts.js
<!-- 一旦通过script标签引入echarts文件,window.echarts,在window下面就有一个echarts对象了-->
<script src="./static/lib/echarts.min.js"></script>
2、在main.js中,将全局的echarts对象挂载到Vue的原型对象上
//使用的时候 this.$echarts
Vue.prototype.$echarts = window.echarts
3、axios请求基准路径的配置
import axios from 'axios'
//http://localhost:3000这个就是后台端口
axios.defaults.baseURL = 'http://localhost:3000/api/'
// 将axios挂载到vue的原型对象上
// 使用 this.$http
Vue.prototype.$http = axios
4、主题切换
在index.html里面引入chalk.js
<script src="./static/theme/chalk.js"></script>
1、数据的存储,在vuex文件中
export default new Vuex.Store({
state: {
theme: 'chalk'
},
mutations: {
changeTheme(state ) {
if(state.theme === 'chalk') {
state.theme = 'vintage'
} else {
state.theme = 'chalk'
}
}
},
})
2、点击切换按钮,修改vuex中的theme数据
changeTheme() {
// 修改vuex中的数据
this.$store.commit('changeTheme')
}
3、各个组件监听theme的变化,将vuex中的theme数据映射为每一个组件的计算属性
import {
mapState } from "vuex";
computed: {
...mapState(