下载模块:npm install vue-cookie --save
//引入
import Vue from 'vue'
import VueCookie from 'vue-cookie'
Vue.use(VueCookie);
//设置cookie
//this指向vue对象
//写法一 :第一个参数key值 第二个参数value值 第三个参数:期限值,到期就会清除
this.$cookie.set('test' , 'Hello world!', 1);
//写法二:
//获取时间对象
var date = new Date;
date.setDate(date.getDate() + 21);
this.$cookie.set('dateObject', '一个日期对象的时间戳', { expires: date });
this.$cookie.set('dateString', '一个日期字符串Tue, 12 Apr 2022 09:10:29 GMT', { expires: date.toGMTString() });//用toGMTString对时间戳转字符串
this.$cookie.set('integer', '期限为七天', { expires: 7 });
this.$cookie.set('stringSuffixY', '期限为一年', { expires: '1Y' });
this.$cookie.set('stringSuffixM', '期限为一个月', { expires: '1M' });
this.$cookie.set('stringSuffixD', '期限为一天', { expires: '1D' });
this.$cookie.set('stringSuffixh', '期限为一小时', { expires: '1h' });
this.$cookie.set('stringSuffixm', '期限为10分钟', { expires: '10m' });
this.$cookie.set('stringSuffixs', '期限为30秒后', { expires: '30s' });
//如果设置了域,就对加上域
this.$cookie.set('test', 'Random value', {expires: 1, domain: 'localhost'}); //domain:域地址 https ://www.baidu.com
//删除cookie字段
this.$cookie.delete('test', {domain: 'localhost'});
参考网址:https://www.npmjs.com/package/vue-cookie#advanced-examples