VueRouter and meta fields

Viewed 3721

According to the VueRouter documentation, it is possible to add meta fields and globally restrict routes based on their values.

After attempting an implementation as outlined, I get an error:

ReferenceError: record is not defined (line 46)

Which corresponds to this line:

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

Here is the file that has the router-guard logic:

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');

Any idea on what I may be doing wrong?

1 Answers
Related