直接拷贝过去就能直接使用,无需改动
我在我的项目文件assets中新建了一个tool.js的文件用来存放公共的方法
1、tool.js的文件内容如下
/** * @author xxxx * @description 保存cookie * @param {String} name 需要存储cookie的key * @param {String} value 需要存储cookie的value * @param {Number} timer 默认存储多少天 */ function setCookie(name,value,timer=1){ var Days = timer; //默认将被保存 1 天 var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString(); } /** * @author xxxx * @description 获取cookie * @param {String} name 需要获取cookie的key */ function getCookie(name){ var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); if(arr != null){ return unescape(arr[2]) }else{ return null } } /** * @author xxxx * @description 删除cookie * @param {String} name 需要删除cookie的key */ function clearCookie(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 { setCookie, getCookie, clearCookie }
2、在mian.js文件中引入tool.js并挂载到vue原型上
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false import tool from './assets/js/tool' Vue.prototype.tool = tool; /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
3、使用:在需要存储,读取,删除cookie的页面中
// 存储cookie this.tool.setCookie('sessionId',res.result.sessionId) // 取出cookie console.log(this.tool.getCookie('sessionId')) // 删除cookie setTimeout(()=>{
等待三秒后再删除 this.tool.clearCookie('sessionId') },3000)