有勇气的牛排博客
☰

Vue项目实操cookie相关操作封装

有勇气的牛排 1173 前端 2023-05-18 22:34:48

知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
知止自律打卡微信小程序

@TOC

1 介绍

在vue中通常使用axios进项http请求,但是axios不带cookie,这里可自己获取cookie,放到参数中进行登录验证等,方法不唯一。

2 utils

cookie.js

/**
 * 读取cookie,
 * 需要注意的是cookie是不能存中文的,如果需要存中文,解决方法是后端先进行编码encode(),
 * 前端取出来之后用decodeURI('string')解码。(安卓可以取中文cookie,IOS不行)
 * */
export const b_getCookie = (c_name) => {
  var name = c_name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) != -1) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

/**
 * 设置cookie
 * c_name: cookie的名字,
 * value : cookie值,
 * expiredays: 过期时间(天数)
 * */
export const b_setCookie = (c_name, value, expiredays) => {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}


/**
 * 删除cookie
 * c_name: cookie的名字,
 * */
export const b_delCookie = (c_name) => {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(c_name);
  if (cval != null)
    document.cookie = c_name + "=" + cval + ";expires=" + exp.toGMTString();
}

3 Test.vue

<template>
  <div>
    <el-row>
      <el-input v-model="input" placeholder="请输入内容"></el-input>
      <el-button @click="getCookie">获取cookie</el-button>
      <el-button @click="setCookie">设置cookie</el-button>
    </el-row>
  </div>
</template>
<script>
  import {b_getCookie, b_setCookie} from "../utils/cookie";

  export default {
    name: "Test",
    data() {
      return {
        input: ''
      }
    },
    methods: {
      getCookie() {
        console.log("==========获取cookie===========")
        let username = b_getCookie("username")
        let password = b_getCookie("password")
        console.log(username);
        console.log(password);
      },
      setCookie() {
        console.log("设置cookie");
        b_setCookie("c_key", "c_value", 30)
      }
    }
  }
</script>

<style scoped>

</style>

标签:

×
×