Cookie的使用(js-cookie插件)

1.js-cookie

  • 一个简单,轻巧的JavaScript API,用于处理Cookie

2.安装

npm install js-cookie --save

3.引用

import Cookies from 'js-cookie'
Vue.prototype.$Cookies = Cookies;

4.创建

<!--作者:zhangfan
页面名称:Cookie的使用(js-cookie插件)--> 
<template>
  <div id="product-list-one">
    <button @click="cookiesSet()">执行cookiesSet</button>
    <button @click="cookiesSet7Day()">执行cookiesSet7Day</button>
    <button @click="cookiesSet7DayCurrentPage()">执行cookiesSet7DayCurrentPage</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "zhangfan",
      email: "2207044692@qq.com"
    };
  },
  computed: {},
  methods: {
    cookiesSet() {
      // /创建简单的cookie
      this.$Cookies.set("name", this.name);
    },
    cookiesSet7Day() {
      //创建有效期为7天的cookie
      this.$Cookies.set("name", this.name, { expires: 7 });
    },
    cookiesSet7DayCurrentPage() {
      //为当前页创建有效期7天的cookie
      this.$Cookies.set("name", this.name, { expires: 7, path: "" });
    }
  }
};
</script>

<style scoped>
</style>

5.取值

<!--作者:zhangfan
页面名称:Cookie的使用(js-cookie插件)--> 
<template>
  <div id="product-list-one">
    <button @click="cookiesGet()">执行cookiesGet</button>
    <button @click="cookiesGetAll()">执行cookiesGetAll</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "zhangfan",
      email: "2207044692@qq.com"
    };
  },
  computed: {},
  methods: {
    cookiesGet() {
      //获取指定key的val
      console.log(this.$Cookies.get("name"));
    },
    cookiesGetAll() {
      获取所有cookie
      console.log(this.$Cookies.get());
    }
  }
};
</script>

<style scoped>
</style>

6.删除值

<!--作者:zhangfan
页面名称:Cookie的使用(js-cookie插件)--> 
<template>
  <div id="product-list-one">
    <button @click="cookiesRemove()">删除cookiesRemove</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "zhangfan",
      email: "2207044692@qq.com"
    };
  },
  computed: {},
  methods: {
    cookiesRemove() {
      //删除指定key的val
      this.$Cookies.remove("name");
      //如果值设置了路径,那么不能用简单的delete方法删除值,需要在delete时指定路径
      // Cookies.set('name', 'value', { path: '' });
      // Cookies.remove('name'); // 删除失败
      // Cookies.remove('name', { path: '' }); // 删除成功
      //注意,删除不存在的cookie不会报错也不会有返回
    }
  }
};
</script>

<style scoped>
</style>
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值