当前位置:首页 > 前端教程

elementui cookies

2026-03-05 21:27:06前端教程

使用 Element UI 与 Cookies 的方法

安装 js-cookie 库

Element UI 本身不直接处理 cookies,但可以结合 js-cookie 库轻松管理 cookies。

npm install js-cookie

设置 Cookies

使用 js-cookie 设置 cookies,支持键值对形式,并可配置过期时间。

elementui cookies

import Cookies from 'js-cookie';

// 设置普通 cookie
Cookies.set('username', 'admin');

// 设置带过期时间的 cookie(7 天后过期)
Cookies.set('token', 'abc123', { expires: 7 });

获取 Cookies

通过键名获取存储的 cookie 值。

elementui cookies

const username = Cookies.get('username');
console.log(username); // 输出 'admin'

删除 Cookies

移除指定的 cookie。

Cookies.remove('username');

在 Vue 组件中使用

结合 Element UI 的表单或弹窗功能,实现登录状态存储。

<template>
  <el-form @submit.native.prevent="handleLogin">
    <el-input v-model="form.username" placeholder="用户名"></el-input>
    <el-input v-model="form.password" type="password" placeholder="密码"></el-input>
    <el-button type="primary" native-type="submit">登录</el-button>
  </el-form>
</template>

<script>
import Cookies from 'js-cookie';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
    };
  },
  methods: {
    handleLogin() {
      // 模拟登录成功
      Cookies.set('token', 'generated-token', { expires: 1 }); // 1 天后过期
      this.$message.success('登录成功');
    },
  },
};
</script>

安全注意事项

  • 避免存储敏感信息(如密码)在 cookies 中。
  • 使用 HttpOnlySecure 标志增强安全性(需后端配合)。
Cookies.set('token', 'abc123', { expires: 7, secure: true });

通过以上方法,可以方便地在 Element UI 项目中集成 cookie 管理功能。

分享给朋友:

相关文章

selectable elementui

selectable elementui

使 ElementUI 组件可选中 ElementUI 默认情况下没有直接提供 selectable 功能的组件,但可以通过以下方法实现可选中效果。 使用 el-checkbox 实现单个选中 通过…

elementui import

elementui import

安装 Element UI 在项目中安装 Element UI 可以通过 npm 或 yarn 完成: npm install element-ui --save # 或 yarn add el…

elementui dllplugin

elementui dllplugin

ElementUI DLLPlugin 配置方法 ElementUI 的 DLLPlugin 是一种 Webpack 插件,用于提升构建性能。通过将不经常变化的依赖库预先编译打包,减少开发时的重复构建…

elementui上线

elementui上线

Element UI 上线流程 Element UI 是一个基于 Vue.js 的桌面端组件库,上线流程涉及项目构建、测试、部署等环节。以下是关键步骤: 构建项目 使用 Vue CLI 或 webp…

elementui仿

elementui仿

ElementUI 仿制实现 仿制 ElementUI 需要理解其核心设计理念和组件实现方式。ElementUI 是一个基于 Vue.js 的组件库,提供丰富的 UI 组件和交互体验。 组件结构分析…

elementui 1.0

elementui 1.0

Element UI 1.0 简介 Element UI 1.0 是基于 Vue.js 2.0 的早期版本组件库,发布于2016年,提供了一套桌面端UI组件,如表单、表格、弹窗等。其设计风格简洁,适合…