VueRouter和元字段

时间:2017-07-21 21:18:38

标签: vue.js vuejs2 vue-router

根据VueRouter文档,可以添加meta fields并根据路由值全局限制路由。

按照概述尝试实施后,我收到错误:

ReferenceError: record is not defined (line 46)

这对应于这一行:

if (!hasCookies(record.meta.cookies)) {

这是具有路由器保护逻辑的文件:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  { 
    path : '/authenticate/:id', 
    component : require ('./components/authenticate.vue'),
    redirect: '/here',
  },

  // can only get here if the passcode has been filled out
  {
    path : '/client/create',
    component : require('./components/createClientForm.vue'),
    meta : {
      cookies: ['passcode_cookie'], // need passcode to be able to create the client
      redirect: '/authenticate/1' // dummy value here for now
    }
  },

  // can only get here if passcode and client form have been completed
  {
    path : '/test/:id',
    component : require('./components/runTest.vue'),
    meta : {
      cookies : ['passcode_cookie', 'client_cookie'],
      redirect : '/client/create'
    }
  }
];

const router = new VueRouter ({
  routes,
  mode: 'history',
});

  function hasCookies (cookies) {
    return cookies.every(cookie => document.cookie.indexOf(cookie) !== -1);
  }

    router.beforeEach((to, from, next) => {
      if (to.matched.some(record => record.meta.cookies)) {
      // this route requires cookies, check if cookies exist
      if (!hasCookies(record.meta.cookies)) {
        next({
          path : record.meta.redirect || '/',
        })
      } else {
        next();
      }
    } else {
      next(); // make sure to always call next()!
    }
  });

const app = new Vue ({
  router
}).$mount('#app');

对我可能做错的任何想法?

1 个答案:

答案 0 :(得分:4)

这里的错误是不言自明的。变量record不在范围内,它不是函数参数,也不是全局变量。 record仅在您传递给some的回调函数中定义。它在发生错误时超出了范围。

请改为尝试:

const record = to.matched.find(record => record.meta.cookies && !hasCookies(record.meta.cookies));
if (record) {
  next({ path: record.meta.redirect || '/' });
} else {
  next();
}