前端使用cookie
步骤一 编写方法cookie.ts
//获取cookie、
const CooieTool = {getCookie: (name: string) => {var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");if (arr = document.cookie.match(reg))return (arr[2]);elsereturn null;},//设置cookie,增加到vue实例方便全局调用setCookie: (c_name: any, value: any, expiredays: any) => {var exdate = new Date();exdate.setDate(exdate.getDate() + expiredays);document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());},//删除cookiedelCookie: (name: any) => {var exp = new Date();exp.setTime(exp.getTime() - 1);var cval = CooieTool.getCookie(name);if (cval != null)document.cookie = name + "=" + cval + ";expires=" + exp.toUTCString();}
}
export default CooieTool
步骤二 main.ts挂载
import CooieTool from './assets/js/cookie'app.config.globalProperties.$CooieTool = CooieTool;// cookie处理
1
2
3
步骤三 使用
// 登录时设置状态
const $CooieTool = getCurrentInstance()?.appContext.config.globalProperties.$CooieTool
$CooieTool.setCookie('isLogin',true,30)
// main.ts中配置全局的路由守卫
let isLogin = CooieTool.getCookie('isLogin')console.log('isLogin', isLogin)if (isLogin) {//判断是否有登录next();} else {//在没有登录或者登录过期的前提下,to下面的path是否为/login,如果不是则页面跳转到登录页面if (to.path == "/login") {next();} else {next({ path: "/login" }); //跳转页面到login页}}