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>