在Vue中如何使用Cookie操作实例

一、安装Cookie

在Vue2.0下,这个貌似已经不需要安装了。因为当你创建一个项目的时候,npm install 已经为我们安装好了。我的安装方式如下:

?
1
2
3
4
5
6
7
# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 安装依赖,走你
$ cd my-project
$ npm install

这是我创建好的目录结构,大家可以看一下:


项目结构

二、封装Cookie方法

在util文件夹下,我们创建util.js文件,然后上代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//获取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等方法,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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的朋友们,可以去恶补一下。后面我们将讲解如何使用它进行布局。登录组件的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<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中设置路由,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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,同时页面跳转到登录页,代码如下。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//这个是请求页面路由的时候会验证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;

猜你喜欢

转载自blog.csdn.net/beichen3997/article/details/80758120
今日推荐