前言
众所周知,vue路由跳转可以通过params和query进行传递参数,我们可以把这两种方式简单理解为POST和GET请求方法,params传递的参数会放在body中,虽然用户看不到具体参数,但是在跳转后的页面刷新会造成参数丢失的问题。query传递的参数会拼在url的后面,在跳转后的页面刷新不会造成参数丢失。但通过query传递的参数会在地址栏显示出来,很不安全。下面我们封装一个全局的路由跳转方法,来对query参数进行加密。
1.引入库crypto-js
npm install crypto-js
2.封装加密、解密方法
import CryptoJS from "crypto-js";
const key = CryptoJS.enc.Utf8.parse("reddatehongzao20"); // 十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse("hongzao20reddate"); // 十六位十六进制数作为密钥偏移量
// 解密方法
export function decryption(word: any): string {
const encryptedHexStr = CryptoJS.enc.Hex.parse(word);
const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
// 加密方法
export function encryption(word: any): string {
const srcs = CryptoJS.enc.Utf8.parse(word);
const encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString().toUpperCase();
}
3.封装全局路由跳转方法
/**
* 打开新路由
* @param params 路由参数
* @param _type 打开方式 1:replace 0或不传:push
*/
$routerPush(
params:
| string
| {
name?: string;
path?: string;
query?: any;
},
_type) {
if (typeof params == "object") {
if (params.hasOwnProperty("query")) {
for (const key in params.query) {
if (params.query.hasOwnProperty(key)) {
// encryption 为封装的加密方法
const paramsKey = encryption(params.query[key]);
params.query[key] = paramsKey;
}
}
// 无论是使用query或params,都可以使用name;
// 如果是path的话,params传参无效
params.name = params.path;
delete params.path;
}
}
if (_type == 1) {
this.$router.replace(params);
} else {
this.$router.push(params);
}
}
总结
以上就是今天的分享!!!