vue2中集成js-cookie案例(基于JavaScript)

时间:2024-11-07 07:38:20

在组件中使用 js-cookie

<template>
  <div>
    <h1>Cookie 示例</h1>
    <button @click="setCookie">设置 Cookie</button>
    <button @click="getCookie">获取 Cookie</button>
    <button @click="deleteCookie">删除 Cookie</button>
    <p>{{ cookieValue }}</p>
  </div>
</template>

<script>
export default {
  name: 'CookieExample',
  data() {
    return {
      cookieValue: '',
    };
  },
  methods: {
    setCookie() {
      this.$cookies.set('example', 'Hello, World!', { expires: 7 }); // 设置 Cookie,有效期为 7 天
      this.cookieValue = this.$cookies.get('example');
    },
    getCookie() {
      this.cookieValue = this.$cookies.get('example'); // 获取 Cookie
    },
    deleteCookie() {
      this.$cookies.remove('example'); // 删除 Cookie
      this.cookieValue = '';
    },
  },
};
</script>

<style scoped>
button {
  margin: 5px;
}
</style>