Summary of background projects:
1. Package localStorage
My specification—create a utils folder under src to store encapsulated js files
Encapsulate localStorage to create saveLocal.js, the code is as follows
let storage = {
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get(key) {
return JSON.parse(localStorage.getItem(key));
},
remove(key) {
localStorage.removeItem(key);
}
};
export default storage;
how to use?
1. Global use (in the vue file), the mian.js file is introduced
import storage from "@/utils/saveLocal.js";//localstorage保存数据 ---后缀名.js可以=省略,下面也是
Vue.prototype.$storage = storage;
//这里用的@代表在src为根目录
use:
this.$storage.get('uid','1')//创建
this.$storage.get('uid')//获取
this.$storage.remove('uid')//移除
2. Partial introduction (in the vue file)
import Storage from "@/utils/saveLocal.js";//localstorage保存数据
use:
Storage.get('uid','1')//创建
Storage.get('uid')//获取
Storage.remove('uid')//移除
3. Partial introduction (in the js file) is consistent with the above
import Storage from "@/utils/saveLocal.js";
use:
Storage.get('uid','1')//创建
Storage.get('uid')//获取
Storage.remove('uid')//移除
2. Package interface and request interception and response interception
My specification—create an api folder under src to store the encapsulated js file
Use data.js for encapsulation interface, config.js for encapsulation request and interception, the code is as follows
First look at config.js
import axios from "axios";
import saveLocal from "@/utils/saveLocal";
import {
Message } from 'element-ui';
import router from '@/router'
// 配置请求的根路径
// axios.defaults.baseURL = "/api";
axios.defaults.baseURL = "http://192.168.3.168:1210";
axios.defaults.timeout = 10000;
//用到cookie需要添加下面代码
// axios.defaults.withCredentials = true;
//请求拦截
axios.interceptors.request.use(
config => {
if (saveLocal.get("session")) {
//判断是否有token,这里session是后台返回的一段字符串,和token一个理
//如果有,请求的时候就加上
config.headers['session'] = saveLocal.get("session")
//上面是我这边后台要求加的方式
//其他项目都是加到Authorization上
//config.headers.Authorization = saveLocal.get("session");
}
return config;
},
error => {
console.log(error, "接口出错了99000");
return Promise.reject(error);
}
);
// 响应拦截
axios.interceptors.response.use(
config => {
// console.log(config)
if (config.data.code == 11004) {
router.push('/login')
}
return config;
},
error => {
Message.error('请重新登录')
console.log(error, "接口出错了");
//下面返回状态码需要看后台的状态码,来跳转,如token过期的之类的,让他去重新登录
// const { status } = error.response
// console.log(error.response)
// if (status == 401) {
// // 页面跳转
// router.push('/login')
// }
return Promise.reject(error);
}
);
//封装post方法
const HttpPost = function (url, params) {
return axios.post(url, params, {
headers: {
//这个看项目需求加,看后台需要添加下面请求头
// 'Content-Type': "application/json;charset=utf-8"
}
})};
//1.封装get方法,不需要在调用时加参数情况如
//定义
//getNew() {
// return //HttpGetN("/terminal_center/v1/data/last_sensor?//type=5");
// },
//调用
//async fun1(){
// let res=await this.$api.getNew()
//}
const HttpGet = function (url, param,
) {
return axios.get(url, {
params: param }, {
headers: {
// 'Content-Type': "application/json;charset=utf-8"
}
})
};
//2.封装get方法,在调用时需要参数情况如
//定义
// device_info(params) {
// return HttpGet("terminal_center/v1/data/device_info", params);
// },
//调用:
//async fun2(){
//let params={
// name:1,
// uid:1
// }
// let res=await this.$api.device_info(params)
//}
const HttpGetN = function (url) {
return axios.get(url, {
headers: {
// 'Content-Type': "application/json;charset=utf-8"
}
});
};
export {
HttpGet, HttpPost, HttpGetN };
Introduce the request method in data.js :
import {
HttpGet, HttpPost, HttpGetN } from "./config";
let Api = {
// 登录
Login(params) {
return HttpPost("/edge_service/v1/user_center/login", params);
},
getNew() {
return HttpGetN("/terminal_center/v1/data/last_sensor?type=5");
},
device_info(params) {
return HttpGet("terminal_center/v1/data/device_info", params);
},
};
export default Api;
1. Global use (in the vue file), mian.js file import, generally import globally, import locally (not recommended, troublesome)
import api from "@/api/data.js"// 接口
Vue.prototype.$api = api;
use:
async login() {
let params = {
account: this.username.trim(),
password: this.$md5(this.password.trim()).toUpperCase(),
};
let res = await this.$api.Login(params);//res表示响应回来的参数
//是不是很方便,很happy
},
Three. Filter packaging
Add the filter.js file under the src utils file as usual
//格式
//export function xx(val){
//val 进行编辑,编辑成你需要的样子
//然后return 出去,就达到过滤效果
//return yy
//}
// 过滤时间格式为2020-08-31 12:03:50
//第一个过滤器 ---我这里val是以秒为单位 所以获取当前时间秒数为:Date.parse(new Date()) / 1000
export function timestampToTime(val) {
var date = new Date(parseInt(val * 1000, 10));
let Y = date.getFullYear();
let M =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1;
let D = date.getDate();
let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
let m =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
let s =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s;
};
Global introduction -in the main.js file
import * as filters from "@/utils/filters.js"; //全局挂载过滤器
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key]);
});
transfer
<p class="time">{
{
time | timestampToTime }}</p>
//tmie是变量 timestampTotime是过滤器里面定义的方法
//本例子是显示时间,而且函数在每隔一秒钟都能获取当前时间
export default {
data() {
return {
time: Date.parse(new Date()) / 1000,
};
},
mounted() {
this.update();
},
methods: {
update() {
setTimeout(() => {
this.time = Date.parse(new Date()) / 1000;
this.update();
}, 1000);
},
},
};
Partial introduction
import * as filters from "@/utils/filters.js";
transfer
let tmie=filters.timestampToTime(item.timestamp).toString();
//item.timestamp是以秒为单位的时间戳
//如:1600910729 这里time结果2020-09-24 09:25:29