Vue-cookie

Vue-cookie

思路

1 如果前后台一体的情况,后台会负责页面的渲染同时会负责设置cookie。

2 但是现在是前后台分离,那么前台会负责拿到cookie数据设置到浏览器上

3 具体就是Vue会从后台拿到cookie数据放到浏览器上。

Vue cookie的使用

安装:前端项目目录下的终端

>: npm install vue-cookie --save

配置:main.js

// 配置cookie
import cookie from 'vue-cookie'
Vue.prototype.$axios = cookie;

使用:组件的逻辑方法中

created() {
    console.log('组件创建成功');
    let token = 'asd1d5.0o9utrf7.12jjkht';
    // 设置cookie默认过期时间单位是1d(1天),默认过期时间是浏览器会话结束的时候
    this.$cookie.set('token', token, 1);
},
mounted() {
    console.log('组件渲染成功');
    let token = this.$cookie.get('token');
    console.log(token);
},
destroyed() {
    console.log('组件销毁成功');
    // 删除是吧token置空
    this.$cookie.delete('token')
    this.$cookies.isKey('token')
}


Vue cookie详细使用

全局设置

// 30天后过期
this.$cookies.config('30d')

this.$cookies.config(new Date(2019,03,13).toUTCString())

this.$cookies.config(60 * 60 * 24 * 30,'');

// window object
window.$cookies.config('30d')

单个name设置

//不写过期时间,默认为1天过期
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX")

// 1天过期,忽略大小写
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1d")
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1D")

// 以秒为单位,设置1天过去
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX",60 * 60 * 24)

// 填写Date对象,明确指定过期时间
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", new Date(2017, 03, 12))

// 填写一个时间字符串,指定过期时间
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", "Sat, 13 Mar 2017 12:25:57 GMT")

//浏览器会话结束时过期
this.$cookies.set("default_unit_second","input_value","0");
 
//永不过期
this.$cookies.set("default_unit_second","input_value",-1); 

字符串单位形式设置

Unit full name
y year
m month
d day
h hour
min minute
s second
this.$cookies.set("token","GH1.1.1689020474.1484362313","60s");  // 60秒后过去

this.$cookies.set("token","GH1.1.1689020474.1484362313","30MIN");  // 30分钟后过去

this.$cookies.set("token","GH1.1.1689020474.1484362313","24d");  // 24天后过期

this.$cookies.set("token","GH1.1.1689020474.1484362313","4m");  // 4个月后过期

this.$cookies.set("token","GH1.1.1689020474.1484362313","16h");  // 16小时后过期

this.$cookies.set("token","GH1.1.1689020474.1484362313","3y");  // 3年后过期
posted @ 2019-11-05 08:20  张明岩  阅读(790)  评论(0编辑  收藏  举报