Store undefined when accessing Vuex from VueRouter.beforeEach() - vue.js

I am trying to access the Vuex store as shown in this article: here
I've wasted a good morning on what I am sure is going to be a simple typo, but It escapes me. Inside the beforeEach() => {} body, I get "store is not defined".
I am using the store from the LoginForm component, and it seems to be there. The Vuex tab in the chrome debugger shows the store contents that I expect. What am I doing incorrect?
Cut-n-paste from the critical code:
src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginForm from '#/components/LoginForm'
import HomePage from '#/components/HomePage'
import store from '#/store'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: '/login',
component: LoginForm
},
{
path: '/home',
component: HomePage,
meta: {requiresAuth: true}
}
]
})
router.beforeEach((to, from, next) => {
// store is undefined here
const IsAuthenticated = store.getters.IsAuthenticated()
if (to.matched.some(record => record.meta.requiresAuth) && !IsAuthenticated) {
next({path: '/login', query: { redirect: to.fullPath }})
} else {
next()
}
})
export default router
EDIT: The export from the store seems to be ok. By keeping a local reference to the imported store and referencing that, it works. Seems to be contextual in my use of beforeEach().
const lStore = store;
router.beforeEach((to, from, next) => {
// store is undefined here, lStore is good to go
const IsAuthenticated = lStore.getters.IsAuthenticated()
...
})

I have a very similar code and the only relevant difference seems to be that I import the store the following way in router/index.js:
import store from '#/store/index';
My entire router.js is:
import Vue from 'vue';
import Router from 'vue-router';
import ProjectPage from '#/pages/ProjectPage';
import store from '#/store/index';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/',
name: 'ProjectPage',
component: ProjectPage,
},
],
});
router.beforeEach((to, from, next) => {
// store is defined here
console.log(store);
debugger;
});
export default router;

This was a tail-chasing exercise in the grandest. The problem was that my getter was not called "IsAuthenticated" (and it also wasn't a function). I allowed myself to get duped by my debugger. Restoring all code back to the original post and changing the getter call to
correct
const IsAuthenticated = store.getters.isAuthenticated
incorrect
const IsAuthenticated = store.getters.IsAuthenticated()
In Chrome, putting a breakpoint on that line of code and attempting to inspect 'isAuthenticated' by hovering your mouse over the code yields the original indicated behavior, even though the line evaluates fine.

I also have similar case. On my case:
I have store with modules. So all modules imported on /store/index.js
On router /router/index.js, I import the store
and then use store getter on router work well
store/index.js
...
import auth from './modules/auth'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
auth
}
})
router/index.js
...
import store from '../store/index.js'
...
router.beforeEach(async (to, from, next) => {
console.log(store.getters['auth/isAuthenticated'])
next()
})

Related

Vue: Can't access Pinia Store in beforeEnter vue-router

I am using Vue 3 including the Composition API and additionally Pinia as State Management.
In the options API there is a method beforeRouteEnter, which is built into the component itself. Unfortunately this method does not exist in the composition API. Here the code, which would have been in the beforeRouteEnter method, is written directly into the setup method. However, this means that the component is loaded and displayed first, then the code is executed and, if the check fails, the component is redirected to an error page, for example.
My idea was to make my check directly in the route configuration in the beforeEnter method of a route. However, I don't have access to the Pinia Store, which doesn't seem to be initialized yet, although it is called before in the main.js.
Console Log
Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
const pinia = createPinia()
app.use(pinia)
This will fail in production.
Router.js
import { useProcessStore } from "#/store/process";
const routes: Array<RouteRecordRaw> = [
{
path: "/processes/:id",
name: "ProcessView",
component: loadView("ProcessView", "processes/"),
beforeEnter: () => {
const processStore = useProcessStore();
console.log(processStore);
},
children: [
{
path: "steer",
name: "ProcessSteer",
component: loadView("ProcessSteer", "processes/")
},
{
path: "approve/:code",
name: "ProcessApprove",
component: loadView("ProcessApprove", "processes/")
}
]
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
main.js
import { createApp } from "vue";
import "#/assets/bundle-bootstrap.css";
import App from "#/App.vue";
import { createPinia } from "pinia";
import router from "#/router";
import SvgIcon from "#/components/SvgIcon.vue";
const pinia = createPinia();
const app = createApp(App);
app.use(pinia);
app.use(router);
app.component("SvgIcon", SvgIcon);
router.isReady().then(() => {
app.mount("#app");
});
However, I don't have access to the Pinia Store, which doesn't seem to be initialized yet, although it is called before in the main.js
Before what? Pinia instance is created with const pinia = createPinia(); after the router module is imported - while it is imported, all side-effects including the call to createRouter() are executed. Once the router is created it begins it's initial navigation (on client - on server you need to trigger it with router.push()) - if you happen to be at URL matching the route with guard that is using Pinia store, the useProcessStore() happens before Pinia is created...
Using a store outside of a component
You have two options:
either you make sure that any useXXXStore() call happens after Pinia is created (createPinia()) and installed (app.use(pinia))
or you pass the Pinia instance into any useXXXStore() outside of component...
// store.js
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia;
// router.js
import pinia from "#/store.js";
import { useProcessStore } from "#/store/process";
const routes: Array<RouteRecordRaw> = [
{
path: "/processes/:id",
name: "ProcessView",
component: loadView("ProcessView", "processes/"),
beforeEnter: () => {
const processStore = useProcessStore(pinia ); // <-- passing Pinia instance directly
console.log(processStore);
},
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
// main.js
import { createApp } from "vue";
import App from "#/App.vue";
import store from "#/store.js";
import router from "#/router";
const app = createApp(App);
app.use(store);
app.use(router);
router.isReady().then(() => {
app.mount("#app");
});
Hope this would be helpful.
Vue provide support for some functions in which we need store(outside of the components).
To fix this problem I just called the useStore() function inside the function provided by Vue(beforeEach) and it worked.
Reference : https://pinia.vuejs.org/core-concepts/outside-component-usage.html
Example :
import { useAuthStore } from "#/stores/auth";
.
.
.
.
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
router.beforeEach(async (to, from) => {
const authStore = useAuthStore();
// use authStore Here
});
I have same problem to access the store in "beforeEach" method for managing authorization.
I use this method in main.js, not in router.js. in router.js store is not accessible.
create pinia instance in piniCreate.js
//piniaCreate.js
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia;
after that create my store in mainStore.js
import { defineStore } from 'pinia'
export const mainStore = defineStore('counter', {
state: () => {
return {
user: {
isAuthenticated: isAuthen,
}
}
},
actions: {
login(result) {
//...
this.user.isAuthenticated = true;
} ,
logOff() {
this.user.isAuthenticated = false;
}
}
});
Then I used beforeEach method in the main.js
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import pinia from "#/stores/piniaCreate";
import { mainStore } from '#/stores/mainStore';
import router from './router'
const app = createApp(App)
.use(pinia)
.use(router)
const store1 = mainStore();
router.beforeEach((from) => {
if (from.meta.requiresAuth && !store1.user.isAuthenticated) {
router.push({ name: 'login', query: { redirect: from.path } });
}
})
app.mount('#app');
You can pass the method in the second parameter of definestore:
store.js
export const useAppStore = defineStore('app', () => {
const state = reactive({
appName: 'App',
appLogo: ''
})
return {
...toRefs(state)
}
})
router.js
router.beforeEach((to, from, next) => {
const apppStore = useAppStore()
next()
})
I have resolved this by adding lazy loading
const routes = [
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=535663ae' does not provide an export named 'default'

I'm using a js framework known as griptape(used for blockchain). I'm getting this error when trying to use the vue router.
import Vue from "vue"; //Error **does not provide an export named 'default'**
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
},
];
const router = new VueRouter({
routes,
});
export default router;
while my vue.d.ts file looks like this
import { CompilerOptions } from '#vue/compiler-dom';
import { RenderFunction } from '#vue/runtime-dom';
export declare function compile(template: string | HTMLElement, options?: CompilerOptions): RenderFunction;
export * from "#vue/runtime-dom";
export { }
router.d.ts file look like this
I think you are using Vue 3. You should check your vue-router version. If you just run npm i vue-router now, the version should be "^3.5.3". Try to use npm i vue-router#next to install newer version.
Then export router like this:
import {createRouter, createWebHistory} from 'vue-router'
const routes = [
{
path:'/',
name:"Home",
component:()=>import('./pages/Home.vue')
}
,
{
path:'/about',
name:"About",
component:()=>import('./pages/About.vue')
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
You technically didn't ask a question I will try to explain the error. Your error states what you try to do, importing a default export from the module 'vue' which doesn't exist.
// some ts file
import Vue from "vue";
// the module
export default {}
If there should be a named export called 'Vue' you should write it as follows: import { Vue } from 'vue'
references:
https://www.typescriptlang.org/docs/handbook/modules.html#default-exports

Problems with the work of preloader vue.js

I'm trying to make showing preloader when i go from one component to another. I use this preloader. I create file loader.js and write there:
import Vue from 'vue';
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';
Vue.use(Loading);
let loader = Vue.$loading.show({
loader: 'dots',
color: '#5D00FF',
zIndex: 999,
});
function loaderStart() {
loader;
}
function loaderEnd() {
loader.hide();
}
export default {loaderStart, loaderEnd}
loader,js i import to the index.js and there i write when i want to call loader start but it does not starting(withoun if in beforeResolve preloader is working). Here is index.js:
import Vue from 'vue'
import Router from 'vue-router'
import Authorization from '#/components/Authorization'
import Main from '#/components/Main'
import loader from './loader'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'Main',
component: Main,
},
{
path: '/authorization',
name: 'Authorization',
component: Authorization
}
]
})
router.beforeResolve((to, from, next) => {
if(to.path) {
loader.loaderStart()
}
next()
});
router.afterEach((to, from) => {
loader.loaderEnd()
});
export default router;
Please, help me find the problem
Your current loader will appear just once because you called show method once as well. You need to invoke show method every loaderStart call and store the loader:
let loader = null;
function loaderStart() {
// it would be better to extract these values as constants
loader = Vue.$loading.show({
loader: 'dots',
color: '#5D00FF',
zIndex: 999,
});
}
function loaderEnd() {
loader.hide();
}
Probably you have some async components since you added loader to routing logic, so you should use the beforeEach hook instead of the beforeResolve one.
router.beforeEach((to, from, next) => {
loader.loaderStart()
next()
});
router.afterEach((to, from) => {
loader.loaderEnd()
});
Loader API docs (show method)
Vue-router guards
Vue-router navigation flow

Vue: beforeEach is not a function

Route change doesn't scroll to top, so Vue creator advises to use navigation guards. In the updated version:
Router.beforeEach(function (to, from, next) {
window.scrollTo(0, 0)
next();
})
Perfect, except it yields this fatal error in my app: ncaught TypeError: vue_router__WEBPACK_IMPORTED_MODULE_1__.default.beforeEach is not a function
Why?
Just in case here's my complete router.js file:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import PastEvents from './views/PastEvents.vue'
import BasicPage from './views/BasicPage.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/past-events',
name: 'past-events',
component: PastEvents
},
{
path: '/basic-page',
name: 'basic-page',
component: BasicPage
}
]
})
Router.beforeEach(function (to, from, next) {
window.scrollTo(0, 0)
next();
})
You've capitalized Router, that's the class name. What you want to do is add your .beforeEach() to the instance of the router. You'll notice in the documentation that it's always a lowercase router they're adding the guards to.
Currently, you're immediately exporting the instance from the module, so you'll need to first add it to a variable when you create a new Router and then add your .beforeEach() clauses to it before finally exporting it.
const router = new Router({
...
})
router.beforeEach( ... )
export default router

Lazy loading on vuex modules

I’m trying to use lazy loading with my vuex modules like this article : https://alexjoverm.github.io/2017/07/16/Lazy-load-in-Vue-using-Webpack-s-code-splitting/
Here is my old store\index.js :
import Vue from 'vue';
import Vuex from 'vuex';
import app from './modules/app';
import search from './modules/search';
import identity from './modules/identity';
import profil from './modules/profil';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
app,
search,
identity,
profil,
},
});
I tried to do this :
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store();
import('./modules/app').then((appModule) => {
store.registerModule('app', appModule);
});
import('./modules/search').then((searchModule) => {
store.registerModule('search', searchModule);
});
import('./modules/identity').then((identityModule) => {
store.registerModule('identity', identityModule);
});
import('./modules/profil').then((profilModule) => {
store.registerModule('profil', profilModule);
});
export default store;
But now I have a lot of error like “TypeError: _vm.consultList is undefined", consultList is a mapState variable, I also have same errors on my mapActions
Did I’ve done something wrong ?
All of those modules will be registered when app is loaded any because you most likely add the store to your initial vue instance. How I dynamically loading my vuex module is via the router:
{
path: "/orders/active",
name: "active-orders",
component: ActiveOrders,
props: true,
beforeEnter: (to, from, next) => {
importOrdersState().then(() => {
next();
});
}
},
Then also inside my router file I added:
const importOrdersState = () =>
import("#/store/orders").then(({ orders }) => {
if (!store.state.orders) store.registerModule("orders", orders);
else return;
});