再梳理一遍
一、商品后台管理系统
1. 功能
1.1 服务端情况
- 开启了CORS跨域支持
- 需要授权的 API ,必须在请求头中使用
Authorization
字段提供token
令牌(axios拦截器) baseUrl
,接口地址:http://localhost:8888/api/private/v1/
token令牌在服务端生成,当登录成功时,post请求返回的用户信息里包含了这一元素:
1.1.1 axios发ajax请求
Axios:通过promise实现对ajax技术的一种封装,ajax只能访问同源的请求。axios并没有install 方法,所以是不能使用vue.use()方法的。为了不在每个文件都引用一次axios,将它改造成vue插件。
- npm安装
- axios发请求
1)使用
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2) 改造为vue插件
plugins/http.js
import axios from 'axios'
const httpHelper = {}
// 配置Vue插件
httpHelper.install = function fn (Vue) {
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1'
Vue.prototype.$http = axios
}
export default httpHelper
main.js里安装插件
import http from '@/plugins/http.js'
Vue.use(http)
1.1.2 拦截器 – 向服务端发请求需要token
httpAxios.install = function (Vue) {
const instance = axios.create({
baseURL: 'http://127.0.0.1:8888/api/private/v1'
})
instance.interceptors.request.use(function (config) {
if (config.url.toLowerCase() !== 'login') {
const token = sessionStorage.getItem('token')
config.headers.Authorization = token
}
return config
}, function (error) {
return Promise.reject(error)
})
Vue.prototype.$http = instance
}
1.1.3 路由导航守卫 – 权限控制
路由的前置守卫 router.js
router.beforeEach((to, from, next) => {
console.log(to, from)
if (to.name === 'login') {
next()
} else {
const token = sessionStorage.getItem('token')
if (!token) {
router.push({ 'name': 'login' })
Message.warning('请先登录')
return
}
next()
}
})
1.1.4 使用async和await
handleLogin () {
this.$http.post('login', this.formData)
.then((res) => {
const data = res.data
const {meta: {status, msg}} = data
if (status === 200) {
const token = data.data.token
sessionStorage.setItem('token', token)
this.$message.success(msg)
} else {
this.$message.error(msg)
}
})
}
async handleLogin () {
const res = await this.$http.post('login', this.formData)
const data = res.data
const { meta: { status, msg } } = data
if (status === 200) {
const token = data.data.token
sessionStorage.setItem('token', token)
this.$message.success(msg)
} else {
this.$message.error(msg)
}
}
外层方法使用async
关键字(await最近的外层函数要加上async),发请求代码前加 await
,省略.then
1.2 自定义组件
以自定义面包屑组件(子组件)为例,父组件(使用到面包屑的组件)向子组件传值。
子组件:
<template>
<!-- 面包屑 -->
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>{
{this.level1}}</el-breadcrumb-item>
<el-breadcrumb-item>{
{this.level2}}</el-breadcrumb-item>
</el-breadcrumb>
</template>
<script>
export default {
name: 'my-bread',
props: ['level1', 'level2']
}
</script>