1.定义
utils/common.js
//获取cookie、
export function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return (arr[2]);
else
return null;
}
//设置cookie,增加到vue实例方便全局调用
export function setCookie(c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};
//删除cookie
export function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};
export default {
getCookie,
setCookie,
delCookie,
}
2.全局
main.js
import cookieStore from '@/utils/common';
Vue.prototype.$cookieStore = cookieStore;
3。获取
在App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
created() {
//初始化全局截取 集成框架url,获取字符串?后面的东西
if (window.location.hash.split("userId")[1] !== undefined) {
let userIdCom= window.location.hash.split("userId")[1].split("=")[1];
console.log("获取到userId",window.location.hash.split("userId")[1],userIdCom);
this.$cookieStore.setCookie("userIdCom", JSON.stringify(userIdCom));//userIdCom
sessionStorage.setItem("common", JSON.stringify(userIdCom));
} else {
console.log("没有获取到userId");
}
}
}
</script>
<style lang="scss">
.app-container {
background-color: #eff3f6;
width: 100%;
}
::-webkit-scrollbar {
width: 9px;
height: 4px;
}
::-webkit-scrollbar-thumb {
border-radius: 5px;
-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
background: rgba(0,0,0,0.1);
}
::-webkit-scrollbar-track {
border-radius: 0;
background: rgba(0,0,0,0.0);
}
</style>
created() {
//初始化全局截取 集成框架url
if (window.location.hash.split("data")[1] !== undefined) {
let url = window.location.hash.split("data")[1].split("=")[1];//获取截取部分
let common = JSON.parse(unescape(url));//将截取部分进行解码
console.log("dwafcommon",common);
//存
this.$cookieStore.setCookie("common", JSON.stringify(common));
//取
//JSON.parse(unescape(this.$cookieStore.getCookie("common")))
//存
sessionStorage.setItem("pageInfo", JSON.stringify(common));
//取
//JSON.parse(sessionStorage.getItem('pageInfo'))
} else {}
- JSON.parse()用法
JSON.parse()方法将JSON格式字符串转换为js对象(属性名没有双引号)。
解析前要保证数据是标准的JSON格式,否则会解析出错。 - JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串
4.使用
import cookieStore from "@/utils/common";
JSON.parse(unescape(cookieStore.getCookie("userIdCom")))//userIdCom
番外:
this.urlhref="yourUrlHref"
let number = 0;
for (let key in FORM) {
if (FORM[key] != null && FORM[key] != '' && FORM[key].length != 0) {
if (key != "comName") {
if (number == 0) {
this.urlhref += "?" + key + "=" + FORM[key];
} else {
this.urlhref += "&" + key + "=" + FORM[key];
}
number++;
}
}
}