nuxt.js中间件实现拦截权限判断的方法
首页 > >    作者:lininn   2019年4月16日 16:09 星期二   热度:3262°   百度已收录  
时间:2019-4-16 16:09   热度:3262° 

项目环境

"element-ui":"^2.3.4",

"flyio":"^0.5.2",

"js-cookie":"^2.2.0",

"nuxt":"^1.4.0",

一:首先登录页面

在登录页面script中引入

?
1
import Cookie from 'js-cookie' //npm install js-cookie --save

在script里加上

?
1
2
3
4
5
6
7
8
9
10
11
data(){
 return{
  redirectURL:'/'
 }
},
mounted() {
  let rediretUrl = this.$route.query.ref;
  if (rediretUrl){
  this.redirectURL = rediretUrl
  }
 }

接着在methods里面编写一个 submitLogin的方法

?
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
submitLogin(ev) {
  var _this = this;
  this.$refs.ruleForm2.validate((valid) => {
   if (valid) {
   _this.logining = true
   var sendData = {
    username: _this.ruleForm2.account,
    password: _this.ruleForm2.pass,
    is_remember: _this.isRemember
   };
   //登录操作
   _this.$https.post('login/index', sendData).then(res => {
    if (res.status == 1) {
    //将服务端的token存入cookie当中
    Cookie.set('token', res.data.token)
    //返回上一页
    _this.$router.push(_this.redirectURL)
    }else{
    _this.$message.warning(res.msg)
    }
   })
   } else {
   return false;
   }
  });
  },

二:nuxt中间件middleware编写权限拦截

新建一个userAuth.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
import utils from '~/utils/utils'
  
export default function ({route, req, res, redirect}) {
 let isClient = process.client;
 let isServer = process.server;
 let redirectURL = '/login';
 var token, path
 //在服务端
 if (isServer) {
 let cookies = utils.getcookiesInServer(req)
 path = req.originalUrl;
 token = cookies.token ? cookies.token : ''
 }
 //在客户端判读是否需要登陆
 if (isClient) {
 token = utils.getcookiesInClient('token')
 path = route.path;
 }
 if (path) {
 redirectURL = '/login?ref=' + encodeURIComponent(path)
 }
 //需要进行权限判断的页面开头
 if (!token) {
  redirect(redirectURL)
 }
}

utils.js里面的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Cookie from 'js-cookie'
export default {
 //获取服务端cookie
 getcookiesInServer:function (req) {
 let service_cookie = {};
 req && req.headers.cookie && req.headers.cookie.split(';').forEach(function (val) {
  let parts = val.split('=');
  service_cookie[parts[0].trim()] = (parts[1] || '').trim();
 });
 return service_cookie;
 },
 //获取客户端cookie
 getcookiesInClient:function (key) {
 return Cookie.get(key) ? Cookie.get(key) : ''
 }
}

到这里,我们的中间件,权限判断依据完成了

三:运用到项目中

在项目中。例如,用户信息设置页面,需要进行是否登录判断

pages/user/setting.vue

我们在页面中运用刚刚编写的userAuth中间。

?
1
middleware: 'userAuth',

现在

setting页面就有权限判断了

二维码加载中...
本文作者:lininn      文章标题: nuxt.js中间件实现拦截权限判断的方法
本文地址:?post=331
版权声明:若无注明,本文皆为“覆手为雨”原创,转载请保留文章出处。
分享本文至:

返回顶部    首页    手机版本    后花园   会员注册   
版权所有:覆手为雨    站长: lininn