Vue3整合cookie

418 阅读1分钟
1、在src下创建utils文件夹,创建cookie.ts文件,内容如下:

`export default class Cookie{

static get(name:string){

    let v = window.document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');

    return v ? v[2] : null;
}

static set(name:string, value:any, days = 1){
    let d = new Date;

    d.setTime(d.getTime() + 24*60*60*1000*days);

    window.document.cookie = name + "=" + value + ";path=/;expires=" + d.toUTCString();
}
static delete(name:string){
    this.set(name, '', -1);
}

} `

2、在main.ts文件中全局注册:

import Cookie from './utils/cookie'

const app = createApp(App)

app.config.globalProperties.$CookieTool = Cookie;//cookie处理

3、在页面中使用:

const CookieTool=getCurrentInstance()?.appContext.config.globalProperties.CookieTool = getCurrentInstance()?.appContext.config.globalProperties.CookieTool

$CookieTool.set("person_id",22933)