如何使Vue-Cookies在Vue-Router组件中工作

时间:2018-08-10 14:57:12

标签: javascript cookies vue.js vuejs2 vue-router

我有一个路由器index.js文件,可以像这样加载Vue,Vue-Router和Vue-Cookies:

import Vue from 'vue';
import Router from 'vue-router';
import VueCookies from 'vue-cookies';

Vue.use(Router);
Vue.use(VueCookies);

然后我定义所有我的路线,如下所示:

const router = new Router({
  routes: [
    {
      path: '*',
      name: 'erorr',
      secure: false,
      component: error404,
    },
    {
      path: '/',
      name: 'Home',
      secure: false,
      component: home,
    },
    {
      path: '/clp',
      name: 'CLP',
      secure: true,
      component: clpHome,
    },
    {
      path: '/saml/login',
      name: 'samlLogin',
      secure: false,
      component: samlLogin,
    },
    {
      path: '/saml/logout',
      name: 'samlLogout',
      secure: false,
      component: samlLogout,
    },
    {
      path: '/user/profile',
      name: 'userProfile',
      secure: false,
      component: userProfile,
    },
  ],
});

此后,它正在检查是否设置了cookie:

router.beforeEach((to, from, next) => {
  // Look at all routes
  router.options.routes.forEach((route) => {
    // If this is the current route and it's secure
    if (((to.matched[0].path === route.path || to.matched[0].path === '')/* && route.path === '/'*/) && route.secure) {
      // Check if there's a cookie and verify it
      // Check if user has cookie "SAMLSession"

这是错误弹出的地方,“ TypeError:无法读取未定义的属性'isKey'”     console.log(this。$ cookies); 也会返回“未定义”。

      if (this.$cookies.isKey('SAMLSession')) {
        // Sets the value of "SAMLSession" cookie to a variable
        const sessionId = this.$cookies.get('SAMLSession');
        // Runs function checkSaml located above, then once that completes....
        checkSaml(sessionId).then(result => {
          // Check if the session id is valid via Express, noted by a response of "OK" if good, and "BAD!" if not valid
          if (result.data === 'OK') {
            // If it's good, allow the user to see the page
            next();
          } else {
            // If it's not valid, set a cookie of the page the user was trying to access and then sign them in
            this.$cookies.set('referLocation', to.path, Infinity, '/');
            next('/saml/login');
          }
        });
      } else {
        // If it's not a cookie, set a cookie of the page the user was trying to access and then sign them in
        this.$cookies.set('referLocation', to.path, Infinity, '/');
        next('/saml/login');
      }
    }
  });
  // If nothing has happened, allow the user to visit the page
  next();
});

该配置已在几天前开始运行,现在不加载VueCookies,在排除故障方面的任何建议将不胜感激。

2 个答案:

答案 0 :(得分:3)

解决方案是将所有“ this。$ cookies”对象更改为“ window。$ cookies”,如下所示:

router.beforeEach((to, from, next) => {
  // Look at all routes
  router.options.routes.forEach((route) => {
    // If this is the current route and it's secure
    if (((to.matched[0].path === route.path || to.matched[0].path === '') && route.path === '/') && route.secure) {
      // Check if there's a cookie and verify it
      // Check if user has cookie "SAMLSession"
      if (window.$cookies.isKey('SAMLSession')) {
        // Sets the value of "SAMLSession" cookie to a variable
        const sessionId = window.$cookies.get('SAMLSession');
        // Runs function checkSaml located above, then once that completes....
        checkSaml(sessionId).then(result => {
          // Check if the session id is valid via Express, noted by a response of "OK" if good, and "BAD!" if not valid
          if (result.data === 'OK') {
            // If it's good, allow the user to see the page
            next();
          } else {
            // If it's not valid, set a cookie of the page the user was trying to access and then sign them in
            window.$cookies.set('referLocation', to.path, Infinity, '/');
            next('/saml/login');
          }
        });
      } else {
        // If it's not a cookie, set a cookie of the page the user was trying to access and then sign them in
        window.$cookies.set('referLocation', to.path, Infinity, '/');
        next('/saml/login');
      }
    }
  });
  // If nothing has happened, allow the user to visit the page
  next();
});

答案 1 :(得分:1)

我遇到了同样的问题,试图弄清为什么this在路由器中未定义,这会导致this.$cookies错误。

这是我的方法。

//add this in the router index.js
import Vue from 'vue'

然后,我可以从cookie访问Vue

beforeEnter: (to, from, next) => {
    let access_token = Vue.cookie.get('access_token')
    if (access_token == null) {
        // user doesn't have access token, redirect to login
        next({ name: 'login' })
    }
    else {
        // user has access token, user can open the page
        next()
    }
},