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

x33g5p2x  于2022-02-17 转载在 Vue.js  
字(1.9k)|赞(0)|评价(0)|浏览(421)

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>

相关文章