title: How to access this variable from my store / state in my vue router?
body: <p>I have setup my routes.js file to import my state from my store.  This is working as when I <code>console.log(state)</code> it outputs my store to console successfully:</p>
  
  <p><a href="https://i.stack.imgur.com/fSoxi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fSoxi.png" alt="enter image description here"></a></p>
  
  <p>I then define my route as below:</p>
  
  <p><strong>routes.js</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>   
  import { state } from './store/store';
  // import { mapState, mapGetters } from "vuex";
  
  console.log(state)
  
  const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
  },
  {
    path: '/project/:id',
    name: 'project',
    component: Project,
    props: true,
    meta: {
      requiresAuth: true,
    },
  
    children: [
          {
            path: 'module/:module',
            name: 'module',
            component: Tasks,
            props: true,
  
            children: [
                    {
                      path: 'task/:url',
                      name: 'task',
                      component:  () =&gt; import(`./components/ProductServiceAnalysis/${$state.taskURL}.vue`),
                      props: true,</code></pre>
  </div>
  </div>
  </p>
  
  <p>I am getting the error:
  <code>app.js:59653 [vue-router] Failed to resolve async component default: ReferenceError: state is not defined</code> in relation to the second last line where I try to access the state.taskURL variable.</p>
  
  <p>Why is this erroring?  And how can I access my taskURL variable in my store from my Router?</p>
  
  <p>If I am approaching this incorrectly then please offer suggestions.</p>
  
  <p><strong>This is my store.js:</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import Vue from 'vue';
  import Vuex from 'vuex';
  import axios from 'axios'
  
  Vue.use(Vuex);
  axios.defaults.baseURL = 'http://buildmybusiness.test/api'
  
  Vue.config.devtools = true;
  
  export const state = {
   token: localStorage.getItem('access_token') || null,
   requiredTask: 'This is my current task',
   currentModule: '1',
   currentModuleName: 'Product &amp; Service Analysis',
   currentTask: '1',
   modules:[],
   tasks:[],
   taskName:[],
   actions:[],
   userId: localStorage.getItem('loggedin_user') || null,
   userName: localStorage.getItem('loggedin_username') || null,
   projects:[],
   currentProjectId: '',
   currentProjectName: '',
   taskURL: 'define-product-service'
  }
  
  export const store = new Vuex.Store({
  
   state,
  
   mutations: {
    SET_MODULES: (state, payload) =&gt; {
     state.modules = payload;
    },
  
    SET_TASKS: (state, tasks) =&gt; {
     state.tasks = tasks;
    },
  
    SET_MODULE_TITLE: (state, moduleTitle) =&gt; {
     state.currentModuleName = moduleTitle
    },
  
    SET_ACTIONS: (state, payload) =&gt; {
     state.actions = payload;
    },
  
    RETRIEVE_TOKEN: (state, token) =&gt; {
     state.token = token;
    },
    DESTROY_TOKEN: (state) =&gt; {
     state.token = null;
    },
    SET_USERID: (state, userid) =&gt; {
     state.userId = userid;
    },
    DESTROY_USERID: (state) =&gt; {
     state.userId = null;
    },
  
  
    SET_USERNAME: (state, username) =&gt; {
     state.userName = username;
    },
    DESTROY_USERNAME: (state) =&gt; {
     state.userName = '';
    },
  
  
    SET_PROJECTS: (state, projects) =&gt; {
     state.projects = projects;
    },
    DESTROY_PROJECTS: (state) =&gt; {
     state.projects = [];
    },
  
  
    SET_PROJECT_ID: (state, projectId) =&gt; {
     state.currentProjectId = projectId;
    },
    SET_PROJECT_NAME: (state, projectName) =&gt; {
     state.currentProjectName = projectName;
    },
  
  
    SET_ACTION_URL: (state, taskURL) =&gt; {
     state.taskURL = taskURL;
    },
  
   },
  
   getters: {
  
    loggedIn(state){
     return state.token !== null;
    },
  
    SelectedTaskURL(state) {
     return state.taskURL;
    }
   },
  
   actions: {
  
    setActionsURL(context, taskURL){
  
     context.commit("SET_ACTION_URL", taskURL);
  
    },
  
    setProject(context, projectDetails){
  
     const projectId = projectDetails.projectId;
     const projectName = projectDetails.projectName;
  
     context.commit("SET_PROJECT_ID", projectId);
      context.commit("SET_PROJECT_NAME", projectName);
  
    },
  
    fetchProjects(context) {
  
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token;
      return axios.get('/project').then(response =&gt; {
  
        const projectNames = response.data.map(project =&gt; project);
        context.commit("SET_PROJECTS", projectNames);
  
      });
    },
  
    getUserDetails(context) {
  
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token;
      return axios.get('/user').then(response =&gt; {
  
  
       const userid = response.data.id
        localStorage.setItem('loggedin_user', userid)
        context.commit("SET_USERID", userid);
  
       const username = response.data.name
        localStorage.setItem('loggedin_username', username)
        context.commit("SET_USERNAME", username);
       });
    },
  
    register(context, data) {
     return new Promise ((resolve, reject) =&gt; {
      axios.post('/register', {
       name: data.name,
       email: data.email,
       password: data.password,
      })
      .then(response =&gt; {
  
       resolve(response)
  
      })
      .catch(error =&gt; {
  
       reject(error);
      })
     })
    },
  
    destroyToken(context){
     axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
  
     if (context.getters.loggedIn){
      return new Promise ((resolve, reject) =&gt; {
       axios.post('/logout')
       .then(response =&gt; {
  
        localStorage.removeItem('access_token')
        context.commit("DESTROY_TOKEN")
        context.commit("DESTROY_USERID")
        context.commit("DESTROY_USERNAME")
        context.commit("DESTROY_PROJECTS")
        resolve(response)
  
       })
       .catch(error =&gt; {
        localStorage.removeItem('access_token')
        context.commit("DESTROY_TOKEN")
        context.commit("DESTROY_USERID")
        context.commit("DESTROY_USERNAME")
        context.commit("DESTROY_PROJECTS")
        reject(error);
       })
      })
  
     }
    },
  
     loadModules(context) {
  
       axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
         return axios.get('/modules').then(response =&gt; {
  
             context.commit("SET_MODULES", response.data);
             });
     },
  
     getTasks(context, moduleDetails){
  
  
      var moduleTitle = moduleDetails.moduleName;
      var moduleTitle = (moduleTitle === undefined) ? moduleTitle = 'Product &amp; Service Analysis' : moduleTitle;
      //console.log(moduleTitle);
  
      var moduleId = moduleDetails.moduleId;
      var moduleId = (moduleId === undefined) ? moduleId = 1 : moduleId;
  
       return axios.get(`project/${context.state.currentProjectId}/module/${moduleId}`)
        .then(response =&gt; {
         context.commit("SET_TASKS", response.data);
  
         context.commit("SET_MODULE_TITLE", moduleTitle);
        });
     },
  
     loadTasks(context, tasks){
  
     },
  
     loadActions(context){
  
  
     },
  
     retrieveToken(context, credentials){
      return new Promise ((resolve, reject) =&gt; {
       axios.post('/login', {
        username: credentials.username,
        password: credentials.password,
       })
       .then(response =&gt; {
        const token = response.data.access_token
  
        localStorage.setItem('access_token', token)
        context.commit("RETRIEVE_TOKEN", token)
        resolve(response)
  
       })
       .catch(error =&gt; {
        console.log(error);
        reject(error);
       })
      })
     },
   }
  
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>my <strong>app.js</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// main.js
  
  require('./bootstrap');
  
  import Vue from 'vue';
  import App from './App.vue';
  import VueRouter from 'vue-router';
  import VueAxios from 'vue-axios';
  import axios from 'axios';
  import routes from './routes';
  import BootstrapVue from 'bootstrap-vue'
  import { store } from './store/store';
  import Vuex from 'vuex'
  
  
  Vue.config.productionTip = false;
  
  Vue.use(VueRouter);
  Vue.use(VueAxios, axios);
  Vue.use(BootstrapVue);
  Vue.use(Vuex);
  
  const router = new VueRouter({
    
    store,
    routes,
    mode: 'history'
  })
  
  router.beforeEach((to, from, next) =&gt; {
    if (to.matched.some(record =&gt; record.meta.requiresAuth)) {
      // this route requires auth, check if logged in
      // if not, redirect to login page.
      if (!store.getters.loggedIn) {
        next({
          name: 'login',
        })
      } else {
        next()
      }
    } else if (to.matched.some(record =&gt; record.meta.requiresVisitor)) {
      // this route requires auth, check if logged in
      // if not, redirect to login page.
      if (store.getters.loggedIn) {
        next({
          name: 'dashboard',
        })
      } else {
        next()
      }
    } else {
      next() // make sure to always call next()!
    }
  })
  
  new Vue({
      store: store,
      router,
      render: h =&gt; h(App)
  }).$mount('#app');
  
  import 'bootstrap/dist/css/bootstrap.css';
  import 'bootstrap-vue/dist/bootstrap-vue.css';</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>If reference to @shazyriver:</strong></p>
  
  <p>I have done as you suggested.  I have put a <code>console.log(</code>./components/ProductServiceAnalysis/${state.taskURL}.vue<code>);</code> before <code>const routes = [ ...</code> which correctly accesses the taskURL property and prints it to console.  However, it still fails with a 'state undefined' when it tries to access the same property from within the route itself - even though it works when accessed outside the <code>const routes = [</code>:</p>
  
  <p><a href="https://i.stack.imgur.com/XL10q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XL10q.png" alt="enter image description here"></a></p>
  
  <p>See console log for detail</p>