Vue.js router only loading component from navigation and not from URL - vue.js

how to solve this error in vuejs-
index.js?3672:101 Uncaught TypeError: Cannot read property 'beforeEach' of undefined

import VueRouter from 'vue-router';
Vue.use(VueRouter);
Vue.use(Router);
export default new Router({
// history:true,
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/Dashboard/dashboard',
name: 'Business Intelligence Platform',
beforeEnter: requireAuth,
component: dashboard
},
export function requireAuth(to, from, next) {
if (!formSubmit()) {
next({
path: '/',
query: { redirect: to.fullPath }
});
} else {
next();
}
}

Related

Vue router i18n redirecting to duplicate locale in route

I Have a vue application with i18n and authentication via naviation guard.
My issue is that when im running:
#click="pushRouteTo(`${$i18n.locale}/list/` + f.id)"
pushRouteTo(route) {
try {
this.$router.push(route);
} catch (error) {
if (!(error instanceof NavigationDuplicated)) {
throw error;
}
}
}
I am getting pushed to example.com/en/en/list/123 instead of example.com/en/list/123
When i place a debugger in my navigation guard it says that my to.path is "/en/en/list/123"
but i am pushing /en/list/123. How can this be?
Does it have something to do with my redirect in my router?
Here is my router.js:
import Vue from 'vue';
import Router from 'vue-router';
import Home2 from './views/Home2.vue';
import Login from './views/Login.vue';
import Register from './views/Register.vue';
import ErrorLanding from './views/ErrorLanding.vue'
import Root from "./Root"
import i18n, { loadLocaleMessagesAsync } from "#/i18n"
import {
setDocumentLang
} from "#/util/i18n/document"
Vue.use(Router);
const { locale } = i18n
export const router = new Router({
mode: 'history',
base: '/',
routes: [
{
path: '/',
redirect: locale,
meta: {authRequired: false},
},
{
path: "/:locale",
component: Root,
meta: {authRequired: false},
children: [
{
name: 'Home',
path: '',
component: Home2,
meta: {authRequired: false},
},
{
name: 'Login',
path: 'login',
component: Login,
},
{
path: 'register',
component: Register,
},
{
path: 'lockedpage',
name: 'lockedpage',
webpackChunkName: "lockedpage",
meta: {authRequired: true},
component: () => import('./views/LockedPage.vue')
},
{
path: '*',
component: ErrorLanding,
name: 'NotFound'
}
]
}
],
router.beforeEach((to, from, next) => {
const { locale } = to.params
const publicPages = [ `/`, `/${locale}`, `/${locale}/`];
const authRequired = !publicPages.includes(to.path);
const loggedIn = localStorage.getItem('user');
const redirect = to.path;
loadLocaleMessagesAsync(locale).then(() => {
setDocumentLang(locale)
}).then(() => {
if (authRequired && loggedIn === null) {
if(to.meta.authRequired === false) {
debugger;
next();
}
else {
debugger;
next({ name: 'Login', query: { redirect: redirect } });
}
} else {
debugger;
next();
}
})
});
The root to this issue was a missing slash in my route.
pushRouteTo(`${$i18n.locale}/list/` + f.id)
should instead be:
pushRouteTo(`${/$i18n.locale}/list/` + f.id)
thats why it was creating a double locale.

Navigating to route returns Maximum call stack size exceeded

I want to navigate the user to /home once he clicks on a box, but currently the redirection does not work and I get this error:
Maximum call stack size exceeded
What is causing this error and how can I fix it?
here is my relevant html:
<router-link to="/home"> <md-button class="view-captable-btn" v-for="item in capTables" :key="item.contractAddress" v-model="capTables" #click="getCapTableId(item.contractAddress, item); getCaptableName(item.label, item)" >
<p>{{item.label}}</p>
<p class="contract-address-p"> {{item.contractAddress}}</p>
</md-button>
</router-link>
my method:
getCapTableId(contractAddress, item) {
let address = item.contractAddress
store.commit('saveCapTableAddress', address)
},
and my protected route logic :
import Vue from 'vue'
import Router from 'vue-router'
import firebase from "firebase/app"
import "firebase/auth"
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/unauthorized',
name: 'Unauthorized',
component: Unauthorized
},
{
path: '/activity-log',
component: ActivityLog,
name: 'ActivityLog'
},
{
path: '/captables',
name: 'CapTables',
component: CapTables,
meta: {
requiresAuth: true
},
},
{
path: '*',
component: NotFound,
name: 'NotFound',
},
],
mode: 'history'
})
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if(requiresAuth && !currentUser) next('/unauthorized')
else if (!requiresAuth && currentUser) next('home')
else next()
});
export default router
I tried using pushing the route with this.$route.push('/home') still doesn' work.

Not redirecting to Login page with router.beforeEach VUEJS

I need help, I've been trying to debug this for hours this is my the whole code for my routing:
I need this to automatically redirect to the login page and it won't redirect with using the router.beforeEach and there is no error on the console.
import Vue from "vue";
import Router from "vue-router";
import store from "../store.js";
import Login from "#/views/Login.vue";
import Home from "#/views/Home.vue"
Vue.use(Router);
let router = new Router({
mode: "hash",
linkActiveClass: "open active",
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: "/home",
name: "Home",
component: Home,
meta: {
requiresAuth: true
},
children: [
]
}, {
path: "/login",
name: "login",
component: Login
},
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
console.log(store.getters.isLoggedIn);
if (store.getters.isLoggedIn) {
next();
return;
}
next("/login");
} else {
next();
}
});
export default router;
Any help would do.

How to correct, Maximum call stack size exceeded, vue-router?

Good day.
I have the following error:
[vue-router] uncaught error during route navigation:
vue-router.esm.js:1897 RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at resolvePath (vue-router.esm.js:597)
at normalizeLocation (vue-router.esm.js:1297)
at Object.match (vue-router.esm.js:1341)
at VueRouter.match (vue-router.esm.js:2461)
at HashHistory.transitionTo (vue-router.esm.js:1865)
at HashHistory.push (vue-router.esm.js:2267)
at eval (vue-router.esm.js:1952)
at router.beforeEach (index.js:116)
at iterator (vue-router.esm.js:1935)
According to the error it is in my file of routes, which I have it in the following way:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../components/Home'
import Vehiculos from '../components/Vehiculos'
import Perfil from '../components/Perfil'
import Login from '../components/Login'
import TutorialIntroduccion from '../components/TutorialIntroduccion'
import Politicas from '../components/Politicas'
import Parqueo from '../components/Parqueo'
import Politicas from '../components/Politicas'
import Historial from '../components/Historial'
import firebase from 'firebase'
Vue.use(Router)
let tutorialVisto = localStorage.getItem("Tutorial");
const router = new Router({
routes: [
{
path: '*',
redirect: '/login'
},
{
path: '/',
redirect: '/tutorial'
},
{
path: '/tutorial',
name: 'tutorial',
component: TutorialIntroduccion,
meta: {
tutorialVisto: tutorialVisto,
autentificado: false
},
beforeEnter: (to, from, next) => {
let tutorialVisto = to.matched.some(record=>record.meta.tutorialVisto);
if (tutorialVisto)next('login');
else next();
}
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/home',
name: 'home',
component: Home,
meta: {
autentificado: true
}
},
{
path: '/parqueo/:id',
name: 'parqueo',
component: Parqueo,
meta: {
autentificado: true
}
},
{
path: '/vehiculos',
name: 'vehiculos',
component: Vehiculos,
meta: {
autentificado: true
}
},
{
path: '/perfil',
name: 'perfil',
component: Perfil,
meta: {
autentificado: true
}
},
{
path: '/politicas',
name: 'politicas',
component: Politicas,
meta: {
autentificado: true
},
},
{
path: '/historial',
name: 'historial',
component: Historial,
meta:{
autentificado: true
}
}
]
})
router.beforeEach((to, from, next) => {
let usuario = firebase.auth().currentUser; //Debe ser otra Promesa si esta autenticado o no.
let autorizacion = to.matched.some(record=>record.meta.autentificado);
let tutorialVisto = to.matched.some(record=>record.meta.tutorialVisto);
if (autorizacion && !usuario) {
next('login');
}
else if (!autorizacion && usuario) {
next('home');
}
else{
next();
}
})
export default router;
The problem arises when I am in the parking lot view and then when I log in, it does not redirect me to the vita login, but it gives me that error and stays in the same view, although it does close the firebase session. If I am in any of the other views, for example, vehicles, profile or main and then I give in closing session does not generate me error.
The session closing code is the following:
linkto(pathname) {
this.$router.push({ path: pathname })
if(pathname=="/login") {
firebase.auth().signOut().then(() => this.$router.replace('login'))
}
},
According to vue router's docs:
{
// will match everything
path: '*'
}
It is usually used to redirect to a 404 page not another route. In your case, you are calling a new route /login and it matches in * as well, which causes the loop and the Maximum call stack size exceeded.
You have multiple spelling mistakes in your next handlers. These calls accept the name of a route, and if you pass it a name of an route that does not exists, it will behave unspecified.
From what I can see is that you are trying to redirect to login, while you actually called the route Login
It happened to me too.
So after my investigation I have found if you are using Vuejs v. 2.* you have to use the vue-router of v. 2.* (not version 3).
Please see the following examaple:
package.json:
"dependencies": {
"vue": "^2.6.11",
"vue-router": "^2.8.1"
router.ts:
import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import { Component } from "vue-router/types/router";
import Home from "#/views/Home.vue";
import NotFound from "#/views/NotFound.vue";
import MyPage from "#/views/MyPage.vue";
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: "/",
name: "Home",
component: Home as Component
},
{
path: "/my-page",
name: "MyPage",
component: MyPage as Component
},
{
// will match everything else
path: '*',
name: "NotFound",
component: NotFound as Component
}
];
const router = new VueRouter({
mode: "history",
routes
});
export default router;

VueRouter's beforeEach causes error: failed to convert exception to string

My console says:
[vue-router] uncaught error during route navigation:
<failed to convert exception to string>
The line that causes that error is the one in main.js:
next('/login')
my main.js file:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'
import App from './App.vue'
import Routes from './routes'
import { store } from './store/store';
Vue.use(VueRouter);
const router = new VueRouter({
routes: Routes
})
router.beforeEach((to, from, next) => {
next('/login');
})
var vm = new Vue({
el: '#app',
store: store,
router: router,
render: h => h(App),
})
My routes.js file:
export default [
{ path: '/', component: Game, cors: true },
{ path: '/login', component: Login },
{ path: '/signin', component: SignIn },
{ path: '/gamerouter', component: GameRouter },
{ path: '/waitingforplayers', component: WaitingForPlayers, name: "buba" },
{ path: '/selectPlayersForTeams', component: SelectPlayersForTeams },
{ path: '/startStatistics', component: StartStatistics },
{ path: '/gamelocked', component: GameLocked },
{ path: '/answering', component: Answering },
]
I also get this error if i put next('/'), but i do not get this error if i write next() or next(false);
Any ideas that might help me fix this?
next has to be called without parameters to confirm navigation, otherwise you will keep triggering the beforeEach hook:
router.beforeEach(function(to, from, next) {
console.log(to.path)
if (to.path !== '/timer') {
next("/timer");
} else {
next();
}
});