在Vue中如何使用Cookie操作实例
大家好,由于公司忙着赶项目,导致有段时间没有发布新文章了。今天我想跟大家谈谈cookie的使用。同样,这个cookie的使用方法是我从公司的项目中抽出来的,为了能让大家看懂,我会尽量写详细点。废话少说,我们直接进入正题。
一、安装cookie
在vue2.0下,这个貌似已经不需要安装了。因为当你创建一个项目的时候,npm install 已经为我们安装好了。我的安装方式如下:
# 全局安装 vue-cli $ npm install --global vue-cli # 创建一个基于 webpack 模板的新项目 $ vue init webpack my-project # 安装依赖,走你 $ cd my-project $ npm install
这是我创建好的目录结构,大家可以看一下:
项目结构
二、封装cookie方法
在util文件夹下,我们创建util.js文件,然后上代码
//获取cookie、 export function getcookie(name) { var arr, reg = new regexp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return (arr[2]); else return null; } //设置cookie,增加到vue实例方便全局调用 export function 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 export function delcookie (name) { var exp = new date(); exp.settime(exp.gettime() - 1); var cval = getcookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.togmtstring(); };
三、在http中把cookie传到后台
关于这点,我需要说明一下,我们这里使用的是axios进行http传输数据,为了更好的使用axios,我们在util文件夹下创建http.js文件,然后封装get,post等方法,代码如下:
import axios from 'axios' //引用axios import {getcookie} from './util' //引用刚才我们创建的util.js文件,并使用getcookie方法 // axios 配置 axios.defaults.timeout = 5000; axios.defaults.baseurl = 'http://localhost/pjm-shield-api/public/v1/'; //这是调用数据接口 // http request 拦截器,通过这个,我们就可以把cookie传到后台 axios.interceptors.request.use( config => { const token = getcookie('session'); //获取cookie config.data = json.stringify(config.data); config.headers = { 'content-type':'application/x-www-form-urlencoded' //设置跨域头部 }; if (token) { config.params = {'token': token} //后台接收的参数,后面我们将说明后台如何接收 } return config; }, err => { return promise.reject(err); } ); // http response 拦截器 axios.interceptors.response.use( response => { //response.data.errcode是我接口返回的值,如果值为2,说明cookie丢失,然后跳转到登录页,这里根据大家自己的情况来设定 if(response.data.errcode == 2) { router.push({ path: '/login', query: {redirect: router.currentroute.fullpath} //从哪个页面跳转 }) } return response; }, error => { return promise.reject(error.response.data) }); export default axios; /** * fetch 请求方法 * @param url * @param params * @returns {promise} */ export function fetch(url, params = {}) { return new promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }) .catch(err => { reject(err) }) }) } /** * post 请求方法 * @param url * @param data * @returns {promise} */ export function post(url, data = {}) { return new promise((resolve, reject) => { axios.post(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) } /** * patch 方法封装 * @param url * @param data * @returns {promise} */ export function patch(url, data = {}) { return new promise((resolve, reject) => { axios.patch(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) } /** * put 方法封装 * @param url * @param data * @returns {promise} */ export function put(url, data = {}) { return new promise((resolve, reject) => { axios.put(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) }
四、在登录组件使用cookie
由于登录组件我用的是element-ui布局,对应不熟悉element-ui的朋友们,可以去恶补一下。后面我们将讲解如何使用它进行布局。登录组件的代码如下:
<template> <el-form ref="accountfrom" :model="account" :rules="rules" label-position="left" label-width="0px" class="demo-ruleform login-container"> <h3 class="title">后台管理系统</h3> <el-form-item prop="u_telephone"> <el-input type="text" v-model="account.u_telephone" auto-complete="off" placeholder="请输入账号"></el-input> </el-form-item> <el-form-item prod="u_password"> <el-input type="password" v-model="account.u_password" auto-complete="off" placeholder="请输入密码"></el-input> </el-form-item> <el-form-item style="width:100%;"> <el-button type="primary" style="width:100%" @click="handlelogin" :loading="logining">登录</el-button> </el-form-item> </el-form> </template> <script> export default { data() { return { logining: false, account: { u_telephone:'', u_password:'' }, //表单验证规则 rules: { u_telephone: [ {required: true, message:'请输入账号',trigger: 'blur'} ], u_password: [ {required: true,message:'请输入密码',trigger: 'blur'} ] } } }, mounted() { //初始化 }, methods: { handlelogin() { this.$refs.accountfrom.validate((valid) => { if(valid) { this.logining = true; //其中 'm/login' 为调用的接口,this.account为参数 this.$post('m/login',this.account).then(res => { this.logining = false; if(res.errcode !== 200) { this.$message({ message: res.errmsg, type:'error' }); } else { let expiredays = 1000 * 60 * 60 ; this.setcookie('session',res.errdata.token,expiredays); //设置session this.setcookie('u_uuid',res.errdata.u_uuid,expiredays); //设置用户编号 if(this.$route.query.redirect) { this.$router.push(this.$route.query.redirect); } else { this.$router.push('/home'); //跳转用户中心页 } } }); } else { console.log('error submit'); return false; } }); } } } </script>
五、在路由中验证token存不存在,不存在的话会到登录页
在 router--index.js中设置路由,代码如下:
import vue from 'vue' import router from 'vue-router' import {post,fetch,patch,put} from '@/util/http' import {delcookie,getcookie} from '@/util/util' import index from '@/views/index/index' //首页 import home from '@/views/index/home' //主页 import right from '@/components/userright' //右侧 import userlist from '@/views/user/userlist' //用户列表 import usercert from '@/views/user/certification' //用户审核 import userlook from '@/views/user/userlook' //用户查看 import usercertlook from '@/views/user/usercertlook' //用户审核查看 import sellbill from '@/views/ticket/sellbill' import buybill from '@/views/ticket/buybill' import changebill from '@/views/ticket/changebill' import billlist from '@/views/bill/list' import billinfo from '@/views/bill/info' import addbill from '@/views/bill/add' import editsellbill from '@/views/ticket/editsellbill' import ticketstatus from '@/views/ticket/ticketstatus' import addticket from '@/views/ticket/addticket' import userinfo from '@/views/user/userinfo' //个人信息 import editpwd from '@/views/user/editpwd' //修改密码 vue.use(router); const routes = [ { path: '/', name:'登录', component:index }, { path: '/', name: 'home', component: home, redirect: '/home', leaf: true, //只有一个节点 menushow: true, iconcls: 'iconfont icon-home', //图标样式 children: [ {path:'/home', component: right, name: '首页', menushow: true, meta:{requireauth: true }} ] }, { path: '/', component: home, name: '用户管理', menushow: true, iconcls: 'iconfont icon-users', children: [ {path: '/userlist', component: userlist, name: '用户列表', menushow: true, meta:{requireauth: true }}, {path: '/usercert', component: usercert, name: '用户认证审核', menushow: true, meta:{requireauth: true }}, {path: '/userlook', component: userlook, name: '查看用户信息', menushow: false,meta:{requireauth: true}}, {path: '/usercertlook', component: usercertlook, name: '用户审核信息', menushow: false,meta:{requireauth: true}}, ] }, { path: '/', component: home, name: '信息管理', menushow: true, iconcls: 'iconfont icon-books', children: [ {path: '/sellbill', component: sellbill, name: '卖票信息', menushow: true, meta:{requireauth: true }}, {path: '/buybill', component: buybill, name: '买票信息', menushow: true, meta:{requireauth: true }}, {path: '/changebill', component: changebill, name: '换票信息', menushow: true, meta:{requireauth: true }}, {path: '/bill/editsellbill', component: editsellbill, name: '编辑卖票信息', menushow: false, meta:{requireauth: true}} ] }, { path: '/bill', component: home, name: '票据管理', menushow: true, iconcls: 'iconfont icon-books', children: [ {path: '/bill/list', component: billlist, name: '已开票据列表', menushow: true, meta:{requireauth: true }}, {path: '/bill/info', component: billinfo, name: '票据详细页', menushow: false, meta:{requireauth: true }}, {path: '/bill/add', component: addbill, name: '新建开票信息', menushow: true, meta:{requireauth: true }} ] }, { path: '/', component: home, name: '系统设置', menushow: true, iconcls: 'iconfont icon-setting1', children: [ {path: '/userinfo', component: userinfo, name: '个人信息', menushow: true, meta:{requireauth: true }}, {path: '/editpwd', component: editpwd, name: '修改密码', menushow: true, meta:{requireauth: true }} ] } ]; const router = new router({ routes });
备注:请注意路由中的 meta:{requireauth: true },这个配置,主要为下面的验证做服务。
if(to.meta.requireauth),这段代码意思就是说,如果requireauth: true ,那就判断用户是否存在。
如果存在,就继续执行下面的操作,如果不存在,就删除客户端的cookie,同时页面跳转到登录页,代码如下。
//这个是请求页面路由的时候会验证token存不存在,不存在的话会到登录页 router.beforeeach((to, from, next) => { if(to.meta.requireauth) { fetch('m/is/login').then(res => { if(res.errcode == 200) { next(); } else { if(getcookie('session')) { delcookie('session'); } if(getcookie('u_uuid')) { delcookie('u_uuid'); } next({ path: '/' }); } }); } else { next(); } }); export default router;
以上就是cookie在项目中的使用,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: JavaScript初学者必看“new”
下一篇: Vue.js学习笔记之修饰符详解