vue query传参(base64编码,解码)小技巧

2,503 阅读1分钟

1、新建一个base64js文件

const Base64 = {
  //加密
  encode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
      function toSolidBytes(match, p1) {
        return String.fromCharCode('0x' + p1);
      }));
  },
  //解密
  decode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function (c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  }
}
export default Base64

2、在main.js文件引入,绑定vue原型

import Base64 from './utils/base64'
Vue.prototype.$Base64 = Base64;

3.在vue文件种使用

1 非对象参数

this.$Base64.encode()//加密
this.$Base64.decode()//解密

2 参数是对象

this.$Base64.encode(JSON.stringify(params))
JSON.parse(this.$Base64.decode(this.$route.query.id))