vuejs - router going to homepage on refresh - javascript

I have the following problem with my vuejs app.
Every refresh on a page other than the home page results in a redirect to the home page.
Here is my router.js
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/project/:slug",
name: "Project",
component: () =>
import(/* webpackChunkName: "about" */ "../views/Project.vue")
},
{
path: "/projecttimeline/",
name: "ProjectTimeline",
component: () =>
import(/* webpackChunkName: "about" */ "../views/ProjectTimeline.vue")
},
{
path: "/privacypolicy/",
name: "PrivacyPolicy",
component: () =>
import(/* webpackChunkName: "about" */ "../views/PrivacyPolicy.vue")
}
];
const router = new VueRouter({
routes,
scrollBehavior() {
document.getElementById("app").scrollIntoView({ behavior: "instant" });
}
});
router.beforeEach((to, from, next) => {
if (!to.query.lang) {
var setLocale = from.query.lang || "ro";
to.query.lang = setLocale;
next({ path: to.path, query: to.query });
} else {
next();
}
});
export default router;
Is this something related to the vue history?

Related

vue-router change mode history i got problem blankpage when access child route such as "/order/callback"

i got problem issue i'll change mode "hash" to "history" then i'm go url website to
localhost:8082/order >>>>> it's okay
if i gone
localhost:8082/order/callback >>>>>>>>>> it'll blank page
in my router set
import Vue from "vue";
import Router from "vue-router";
const $ROLE = getRole;
Vue.use(Router);
const router = new Router({
mode: "history",
linkExactActiveClass: "active",
routes: [
{
path: "/order",
name: "linetest",
component: () =>
import(/* webpackChunkName: "demo" */ "./views/LineLiff/CancelOrder.vue"),
meta: {
guest: true,
},
},
{
path: "/order/callback",
name: "linetest",
component: () =>
import(/* webpackChunkName: "demo" */ "./views/LineLiff/CancelOrder.vue"),
meta: {
guest: true,
},
},
],
});
export default router;
help me this how to fix vue-router

Vue route only works after visiting root URL first

I'm using Vue Router to redirect https://example.com/foo to https://example.com/foo/randomID.
This only works if the root URL https://example.com are visited first - otherwise a direct call of https://example.com/foo results in a 404 not found.
I can't figure out the root cause of this.
What I've tried so far:
New build
Update NPM packages
Clean install on server
Clean Site Data via Chrome Dev Tools
router.js:
import Vue from 'vue'
import Router from 'vue-router'
import Head from 'vue-head'
import Home from '#/views/Home'
import CheckLogin from '#/views/CheckLogin'
import { isNil } from 'lodash'
import store from '#/store'
Vue.use(Router)
/* If you don't know about VueHead, please refer to https://github.com/ktquez/vue-head */
Vue.use(Head, {
complement: process.env.VUE_APP_TITLE
})
/* If you don't know about VueRouter, please refer to https://router.vuejs.org/ */
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/home',
name: 'home',
component: Home,
meta: {
authNotRequired: true
}
},
{
path: '/check-login',
name: 'check-login',
component: CheckLogin,
meta: {
authNotRequired: true
}
},
{
path: '/login',
name: 'login',
component: () =>
import(
/* webpackChunkName: "client-chunk-login" */ '#/views/Login.vue'
),
meta: {
authNotRequired: true
}
},
{
path: '/products',
name: 'products',
component: () =>
import(
/* webpackChunkName: "client-chunk-products" */ '#/views/Products.vue'
)
},
{
path: '/item/:id',
name: 'item',
props: true,
component: () =>
import(
/* webpackChunkName: "client-chunk-product-details" */ '#/views/Item.vue'
)
},
{
path: '/list/:id',
name: 'list',
props: true,
component: () =>
import(
/* webpackChunkName: "client-chunk-product-details" */ '#/views/List.vue'
),
meta: {
authNotRequired: true
}
},
{
path: '/list',
name: 'listredirect',
props: true,
component: () =>
import(
/* webpackChunkName: "client-chunk-product-details" */ '#/views/Listredirect.vue'
),
meta: {
authNotRequired: true
}
},
{ path: '*', redirect: '/home' }
]
})
/**
* Handle user redirections
*/
// eslint-disable-next-line consistent-return
router.beforeEach((to, from, next) => {
if (
!(to.meta && to.meta.authNotRequired) &&
isNil(store.state.authentication.user)
) {
const path =
store.state.authentication.user === null ? '/login' : '/check-login'
return next(`${path}?redirectUrl=${to.path}`)
}
next()
})
export default router
The vue.config.production.js:
const path = require('path')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') // eslint-disable-line
.BundleAnalyzerPlugin
const PrerenderSPAPlugin = require('prerender-spa-plugin') // eslint-disable-line
const prerenderedRoutesList = ['/login', '/home', '/']
// TODO stats raus aus dist -> plugin ganz raus?!
module.exports = {
configureWebpack: {
plugins: [
/* Refer to https://www.npmjs.com/package/webpack-bundle-analyzer for more details */
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true
}),
/* See https://github.com/chrisvfritz/prerender-spa-plugin for more details */
new PrerenderSPAPlugin({
// Required - The path to the webpack-outputted app to prerender.
staticDir: path.join(__rootDirname),
// Required - Routes to prerender.
routes: prerenderedRoutesList
})
]
}
}
The redirect component:
<template>
<div>
{{ this.$router.push('/list/new') }}
</div>
</template>
Any ideas on how to fix this issue are appreciated.
Maybe you could use Vue Router redirect function? Eg.
routes: [
{ path: '/foo', redirect: to => {
// code you need...
return "/foo/id";
}}
]
basically you need to redirect your 404 hits to index.html, then the path will resolve correctly. Read here for more information
You can use redirect in the vue-router
routes: [
{ path: '/foo', redirect: '/foo/:randomId' }
]
this.$route.params.randomId will be in the component.
Have a look at docs here

Error: Redirected when going from "/login" to "/home" via a navigation guard. Vue-router and firebase-authentication

I have an app with Vue.js and Firebase, and I'm using the firebase authentication to login in my app, but i want to create a beforeEach method so I can add a verification with the firebase auth works. I want to compare the displayName value to let the user sign in, but when i use the else if the error appears and doesn't work.
My router file
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import firebase from 'firebase/app';
import 'firebase/auth';
Vue.use(VueRouter)
const routes = [
{
path: '*',
redirect: '/login'
},
{
path:'/',
redirect: '/login'
},
{
path: '/home',
name: 'Home',
component: Home,
meta: {
requiresAuth: true
}
},
{
path: '/quotations',
name: 'Quotations',
component: () => import(/* webpackChunkName: "quotations" */ '../views/Quotations.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/login',
name: 'Login',
component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue')
},
{
path: '/sign-up',
name: 'SignUp',
component: () => import(/* webpackChunkName: "login" */ '../views/SignUp.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
router.beforeEach((to, from, next) =>{
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if(requiresAuth && !currentUser )next('login');
else if(!requiresAuth && currentUser) next('home');
// I want to compare if the user thats is loggin has the displayName === "3" to enter in my app
else if(requiresAuth && currentUser && currentUser.displayName != "3")next('login');
else next();
});
In the line else if(requiresAuth && currentUser && currentUser.displayName != "3")next('login'); the error appears, but i don't know how to fix this.
Your first else if condition is always considered and met before your 2nd else if since it is less specified than your 2nd. So 2nd else if will not be reached. You should switch those.

Vue router doesn't recognize :lang as a param

I have the following code:
import Router from 'vue-router';
let mainRoutes = [
{path: '/first', component: () => import('./pages/First')},
{path: '/second', component: () => import('./pages/Second')},
{path: '/third', component: () => import('./pages/Third')},
];
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return {x: 0, y: 0}
},
routes: [
{
path: '/:lang',
component: () => import('./layouts/Main'),
children: mainRoutes,
meta: {requiresAuth: true, permissions: true}
},
{
path: '*',
component: () => import('#/pages/errors/404')
}
]
})
router.beforeEach((to, from, next) => {
if (!to.query.lang) {
to.query.lang= 'ru';
next({ path: to.path, query: to.query });
} else {
next();
}
});
export default router
What I want:
Every time some route is entered, I want the vue-router to check whether it has the lang param or not. If not, I want it to place 'ru' in there, if yes then proceed and show the page with the necessary lang (the part which i18n is responsible for).
The problem is that it doesn't recognize ':lang' as a param for the children routes for some reason, so if I try to go to 'test.test/ru', it returns the lang param ok, but if I try 'test.test/ru/first' it doesn't see it and returns 404.
Everything works in case I put :lang param before every child component but it's not really practical. Is there any better way to solve this issue?
With a code like this you should get the effect you want.
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VueRouter from 'vue-router';
import Router from './Router.vue';
import En from './translation/En.vue';
import Ru from './translation/Ru.vue';
Vue.use(VueI18n);
Vue.use(VueRouter);
Vue.use(VueBus);
const messages = {
en: En,
ru: Ru,
};
const i18n = new VueI18n({
fallbackLocale: 'ru',
locale: 'ru',
messages,
});
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/:lang',
component: {
render: (h) => h('router-view'),
},
children: [your children route],
});
router.beforeEach((to, from, next) => {
const { lang } = to.params;
if (!['en', 'fr'].includes(lang)) {
return next(i18n.locale);
}
if (i18n.locale !== lang) {
i18n.locale = lang;
}
return next();
});
I'm not sure but without i18n I think it's that :
...
router.beforeEach((to, from, next) => {
const { lang } = to.params;
if (!['en', 'ru'].includes(lang)) {
route.params.lang = 'ru';
router.push({ name: route.name });
}
});
I've finally found a solution!
If you have some param in the main route, your children routes shouldn't start with a '/' symbol, but simply with the correct route, for instance
let mainRoutes = [
{path: 'first', component: () => import('./pages/First')},
{path: 'second', component: () => import('./pages/Second')},
{path: 'third', component: () => import('./pages/Third')},
];
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return {x: 0, y: 0}
},
routes: [
{
path: '/:lang',
component: () => import('./layouts/Main'),
children: mainRoutes,
meta: {requiresAuth: true, permissions: true}
},
]
})

Vue Router should not redirect if user is logged in

I use Firebase auth with Vuejs and Vue Router.
I have the pages Home, Login, SignUp and Tasks.
I want that when the user is logged in and goes to the Login or SignUp page he will get redirected to the Tasks page but if he goes to the Home page he should not get redirected to the Tasks page. I don't know how to configure this and ask for help.
I have the following code:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/signup',
name: 'SignUp',
component: SignUp
},
{
path: '/tasks',
name: 'Tasks',
component: Tasks,
meta: {
requiresAuth: true
}
},
{ path: "*", redirect: {path: '/'} }
]
const router = new VueRouter({
mode: "history",
routes
});
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) next('login');
else if (!requiresAuth && currentUser){next('tasks')}
else next();
});
let app;
firebase.auth().onAuthStateChanged(function () {
if(!app){
new Vue({
router,
render (h) {
return h(App)
}
}).$mount('#app');
}
});
Solution
I have added a meta tag to the Home path and added an if clause in the router function.
Solution code :
const routes = [
{
path: '/',
name: 'Home',
component: Home,
// I added this meta tag to the Home path.
meta: {
loggedin: true
}
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/signup',
name: 'SignUp',
component: SignUp
},
{
path: '/tasks',
name: 'Tasks',
component: Tasks,
meta: {
requiresAuth: true
}
},
{ path: "*", redirect: {path: '/'} }
]
const router = new VueRouter({
mode: "history",
routes
});
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const loggedin = to.matched.some(record => record.meta.loggedin);
// I added the if clause under this text.
if (loggedin && currentUser) next();
else if (requiresAuth && !currentUser) next('login');
else if (!requiresAuth && currentUser) next('tasks');
else next();
});
let app;
firebase.auth().onAuthStateChanged(function () {
if(!app){
new Vue({
router,
render (h) {
return h(App)
}
}).$mount('#app');
}
});

Categories

Resources