Related
I have an application in vue with vue router that works correctly, also in the router I use navigation guards to protect my routes, the problem is that now I want to have routes or components that work outside the navigation guards, for example a page of password recovery that the user receives a link and can access it directly, my problem is that i want to access to a recovery password direct from a external link it always redirects me to the login, I share my code:
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: Home,
meta: {
user_type: 1
}
},
{
path: '/check-balance',
name: 'check-balance',
component: CheckBalanceComponent,
meta: {
user_type: 1
}
},
{
path: '/check-payment',
name: 'check-payment',
component: CheckPaymentsComponent,
meta: {
user_type: 1
}
},
{
path: '/payment-disabled',
name: 'payment-disabled',
component: DisabledMakePaymentComponent,
meta: {
user_type: 1
}
},
{
path: '/handle-payment',
name: 'handle-payment',
component: HandlePaymentsComponent,
meta: {
user_type: 1
}
},
{
path: '/handle-report',
name: 'handle-report',
component: HandleReportsComponent,
meta: {
user_type: 1
}
},
{
path: '/user-profile',
name: 'user-profile',
component: UserProfileComponent,
meta: {
user_type: 1
}
},
{
path: '/recover-password',
name: 'recover-password',
component: RecoverPasswordComponent,
meta: {
free: 1 //this outside navigation guards
}
},
{
path: '/recover-link',
name: 'recover-link',
component: RecoverLinkComponent,
meta: {
free: 1
}
},
{
path: '/login',
name: 'login',
component: LoginComponent,
meta: {
free: 1
}
},
{
path: '/help',
name: 'help',
component: HelpComponent,
meta: {
user_type: 1
}
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.free)){
next()
}
else if(store.state.user && store.state.user.user_type == 1){
next()
}
else {
next({
name: 'login'
})
}
})
export default router
When i use refresh button in my browser or hit f5 on keyboard instead of refreshing my page it redirects to home page.
Code
router.js
import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);
import NotFoundComponent from './components/NotFoundComponent.vue';
const router = new VueRouter({
mode: "history",
routes: [
{
path: '*',
name: 'notFound',
component: NotFoundComponent,
meta: {
breadCrumb: 'Not Found'
}
},
//rest of routes...
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.admin)) {
if (store.getters.loggedUser.type !== 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
next()
});
router.afterEach((to, from) => {
Vue.nextTick(() => {
document.title = to.pageTitle || 'Test App';
});
});
export default router;
For instance if i am in this URL
https://example.com/products
after refresh i will redirect to
https://example.com
Any idea?
Update
route.js full code
import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);
//admins
import pageHome from './components/HomePage.vue';
import Dashboard from './components/admin/Dashboard.vue';
import AdminProducts from './components/admin/Products/Products.vue';
import AddProducts from './components/admin/Products/Add.vue';
import CurrencySettings from './components/admin/Settings/Currencies/Currency.vue';
import AddCurrencies from './components/admin/Settings/Currencies/Add.vue';
import editCurrencies from './components/admin/Settings/Currencies/Edit.vue';
import SlideSettings from './components/admin/Settings/Slides/Slide.vue';
import addSlides from './components/admin/Settings/Slides/Add.vue';
import editSlides from './components/admin/Settings/Slides/Edit.vue';
import categoriesSettings from './components/admin/Categories/Categories.vue';
import addCategories from './components/admin/Categories/Add.vue';
import editCategories from './components/admin/Categories/Edit.vue';
import tagsSettings from './components/admin/Tags/Tags.vue';
import addTags from './components/admin/Tags/Add.vue';
import editTags from './components/admin/Tags/Edit.vue';
import brandsSettings from './components/admin/Brands/Brands.vue';
import addBrands from './components/admin/Brands/Add.vue';
import editBrands from './components/admin/Brands/Edit.vue';
import usersSettings from './components/admin/Users/Users.vue';
import addUsers from './components/admin/Users/Add.vue';
import editUsers from './components/admin/Users/Edit.vue';
import reviewsSettings from './components/admin/Reviews/Reviews.vue';
import editReviews from './components/admin/Reviews/Edit.vue';
// users
import Register from './components/auth/Register.vue';
import Login from './components/auth/Login.vue';
import Profile from './components/auth/Profile.vue';
import SingleProduct from './components/Front/SingleProduct.vue';
import NotFoundComponent from './components/NotFoundComponent.vue';
const router = new VueRouter({
mode: "history",
routes: [
{
path: '*',
name: 'notFound',
component: NotFoundComponent,
meta: {
breadCrumb: 'Not Found'
}
},
// ADMIN ROUTES
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
name: 'dashboard',
breadCrumb: 'Dashboard'
}
},
{
path: '/dashboard/products',
name: 'adminProducts',
component: AdminProducts,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Products'
}
},
{
path: '/dashboard/products/add',
name: 'addProducts',
component: AddProducts,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Product'
}
},
{
path: '/dashboard/currencies',
name: 'CurrencySettings',
component: CurrencySettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Currencies'
}
},
{
path: '/dashboard/currencies/add',
name: 'addCurrencies',
component: AddCurrencies,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Currency'
}
},
{
path: '/dashboard/currencies/:id/edit',
name: 'editCurrencies',
component: editCurrencies,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Currency'
}
},
{
path: '/dashboard/slides',
name: 'SlideSettings',
component: SlideSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Slides'
}
},
{
path: '/dashboard/slides/add',
name: 'addSlides',
component: addSlides,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Slide'
}
},
{
path: '/dashboard/slides/:id/edit',
name: 'editSlides',
component: editSlides,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Slider'
}
},
{
path: '/dashboard/categories',
name: 'categoriesSettings',
component: categoriesSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Categories'
}
},
{
path: '/dashboard/categories/add',
name: 'addCategories',
component: addCategories,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Category'
}
},
{
path: '/dashboard/categories/:id/edit',
name: 'editCategories',
component: editCategories,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Category'
}
},
{
path: '/dashboard/tags',
name: 'tagsSettings',
component: tagsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Tags'
}
},
{
path: '/dashboard/tags/add',
name: 'addTags',
component: addTags,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Tag'
}
},
{
path: '/dashboard/tags/:id/edit',
name: 'editTags',
component: editTags,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Tag'
}
},
{
path: '/dashboard/brands',
name: 'brandsSettings',
component: brandsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Brands'
}
},
{
path: '/dashboard/brands/add',
name: 'addBrands',
component: addBrands,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add Brand'
}
},
{
path: '/dashboard/brands/:id/edit',
name: 'editBrands',
component: editBrands,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Brand'
}
},
{
path: '/dashboard/users',
name: 'usersSettings',
component: usersSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Users'
}
},
{
path: '/dashboard/users/add',
name: 'addUsers',
component: addUsers,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Add User'
}
},
{
path: '/dashboard/users/:id/edit',
name: 'editUsers',
component: editUsers,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit User'
}
},
{
path: '/dashboard/reviews',
name: 'reviewsSettings',
component: reviewsSettings,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Reviews'
}
},
{
path: '/dashboard/reviews/:id/edit',
name: 'editReviews',
component: editReviews,
meta: {
requiresAuth: true,
admin: true,
layout: 'admin',
breadCrumb: 'Edit Review'
}
},
// public routes
{
path: "/",
name: 'home',
component: pageHome,
meta: {
breadCrumb: 'Home Page'
}
},
{
path: "/products/:slug",
name: 'SingleProduct',
component: SingleProduct,
meta: {
breadCrumb: 'Product'
}
},
// auth
{
path: '/profile',
name: 'profile',
component: Profile,
meta: {
requiresAuth: true,
breadCrumb: 'Profile'
}
},
{
path: '/register',
name: 'register',
component: Register,
meta: {
breadCrumb: 'Register'
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
breadCrumb: 'Login'
}
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.admin)) {
if (store.getters.loggedUser.type !== 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
next()
});
router.afterEach((to, from) => {
Vue.nextTick(() => {
document.title = to.pageTitle || 'Test App';
});
});
export default router;
Solved
working code
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.isLoggedIn) {
next({
name: 'login'
})
} else {
next()
}
}
if (to.matched.some(record => record.meta.requiresAdmin)) {
// this route requires auth, check if logged in
// if not, redirect to home page.
if (!store.getters.loggedUser.type == 'admin') {
next({
name: 'home'
})
} else {
next()
}
}
else {
next() // make sure to always call next()!
}
})
Hope it help others.
When I press refresh(F5) button then my router directs me to the main page. How do I stay on the same page when the page is refreshed?
that's route, mode is 'history'
const routes = [
{ path: '*', redirect: '/' },
{
path: '/', component: template_Default, redirect: '/Login',
children: [
{ path: 'Login', component: login_, name: 'Login' },
{ path: 'SignUp', component: signUp_, name: 'SignUp' }
]
},
{
path: '/Main', component: template_Home, name: 'Main', redirect: '/Main/Overview',
children: [
{ path: 'Overview', component: overview_, name: 'Overview' },
{ path: 'Customer', component: customer_, name: 'Customer' },
{ path: 'Task', component: task_, name: 'Task' },
{ path: 'Order', component: order_, name: 'Order' },
{ path: 'Product', component: product_, name: 'Product' },
{ path: 'Setting', component: setting_, name: 'Setting' }
]
},
{
path: '/ForgotPassword', component: forgotPassword_, name: 'ForgotPassword',
// redirect: '/ForgotPassword/GetEmail',
// children: [
// { path: 'GetEmail', component: forgotPasswordGetEmail, name: 'GetEmail' },
// { path: 'ReSend', component: forgotPasswordReSend, name: 'ReSend' }
// ]
}
]
And my controller,
router.beforeEach((to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const publicPages = ['/Login','/SignUp','/ForgotPassword'];
const authRequired = !publicPages.includes(to.path);
const loggedIn = store.getters.isLoggedIn;
if (authRequired && !loggedIn) {
return next('/Login');
}else next();
if(loggedIn){
AuthController.IsOnline();
}
})
thanks in advance..
The issue is that you have { path: '*', redirect: '/' } as the first item in your routes array. According to the documentation:
When using asterisk routes, make sure to correctly order your routes so that asterisk ones are at the end.
This is because Vue Router searches through your list of routes in order and returns the first matching route. An asterisk is going to match any and all routes so, when you refresh the page, it returns the first route and redirects you to '/'.
Same problem here, but my route have no { path: '*', redirect: '/' }
Here is my code.
export const routes = [
{
path:'/login',
component: login,
name: 'home'
},
{
path:'/',
component: mainapp,
name: 'mainapp',
meta: {
requiresAuth: true
},
children: [
{
path:'/dash',
component: dashboard,
name: 'dashboard'
},
{
path:'/dept',
component: dept,
name: 'department'
},
{
path: '/deptDetail',
component: deptDetail,
name: 'detail'
},
{
path:'/hrd',
component: HRD
},
{
path:'/notify',
component: notify
},
{
path:'/device',
component: device
},
{
path:'/setup',
component: setup,
name: 'setup'
},
{
path:'/scanArea',
component: area,
},
{
path:'/env',
component: environment,
},
{
path:'/record', /* debug page */
component: record,
},
{
path:'/redis', /* debug page */
component: redis,
},
{
path:'/permit',
component: permit,
},
{
path:'/app',
component: app,
}
]
},
]
I have a problem when trying to make breadcrumb with vuejs, when the routes do not have parameters, it works, but for those routes that need a parameter, I do not know how to have the parameter in breadcrumb
Routes
{
path: '/',
component: () => import('#/components/kit/index'),
name: 'Home',
meta: {
requiresAuth: false,
visibleAfterLogin: true,
breadcrumb: [
{ name: 'Home' }
]
}
},
{
path: '/',
component: () => import('#/pages/kit/Layout'),
children: [
{
path: 'otherouter/:name',
name: 'Other',
components: {
default: () => import('#/components/kit/Other1'),
sidebar: () => import('#/components/kit/Sidebar')
},
meta: {
requiresAuth: false,
visibleAfterLogin: true,
breadcrumb: [
{ name: 'Home', link: 'Home' },
{ name: 'Other' }
]
}
},
{
path: 'studybook/:book',
name: 'Kit',
components: {
default: () => import('#/components/kit/TypeTrails'),
sidebar: () => import('#/components/kit/Sidebar')
},
meta: {
requiresAuth: false,
visibleAfterLogin: true,
breadcrumb: [
{ name: 'Home', link: 'Home' },
{ name: 'Trilhas', link: 'Other' },
{ name: 'Caderno de estudo' }
]
}
}
]
}
Breadcrumb.vue
<template>
<ul class="breadcrumbs">
<li v-for="(item, index) in breadcrumbList" :key="item.name">
<icon name="breadcrumb" size="13px" v-if="index === 0" #click="to(item)" />
{{item.name}}
<strong v-else>{{item.name}}</strong>
</li>
</ul>
</template>
<script>
export default {
data(){
return{
breadcrumbList: []
}
},
mounted(){
this.breadcrumbList = this.$route.meta.breadcrumb
},
watch: {
'$route' (){
this.breadcrumbList = this.$route.meta.breadcrumb
}
},
methods: {
to(item){
if(item.link){
this.$router.push({name: item.link})
}
}
}
}
</script>
maybe too late but you can achieve this making the breadcrumb a function receiving the route object for example:
// router file
{
path: '/items/:id',
...,
meta: {
breadcrumb: (route) => ([
{
name: 'My Items Index view',
to: { name: 'ItemIndex' }
},
{
name: 'My Item Detail view',
to: {
name: 'ItemDetail',
params: { id: route.params.id }
}
}
])
}
}
// app-bar or similar file
export default {
name: 'AppBar',
computed: {
breadcrumb() {
return this.$route.meta.breadcrumb(this.$route)
}
}
}
I'm having trouble running my Vue.js application on a server. It works fine when I'm running locally on macOS or windows. This is the error I get when running 'npm run dev':
These dependencies were not found:
* #/components/account/Profile in ./src/router/index.js
* #/components/account/Plan in ./src/router/index.js
* #/components/account/Team in ./src/router/index.js
* #/components/account/Integration in ./src/router/index.js
* babel-runtime/helpers/extends in ./src/store/index.js
I have checked that the same version of Vue.js is installed -> vue#2.5.13 + really have no clue how to fix this problem. I'm guessing it's a dependency/OS error because it runs with no errors locally.
Does anyone know to fix this or point me somewhere useful? Any help is hugely appreciated!
Edit***
Contents of Index.js below - I'm using Webpack.
import store from '../store'
import Vue from 'vue'
import Router from 'vue-router'
import Home from '#/components/Home'
import Error404 from '#/components/404'
import Login from '#/components/Login'
import Register from '#/components/Register'
import FreeTrial from '#/components/FreeTrial'
import Product from '#/components/Product'
import Services from '#/components/Services'
import Team from '#/components/Team'
import Pricing from '#/components/Pricing'
import Help from '#/components/Help'
import SharedList from '#/components/SharedList'
import ListView from '#/components/App/ListView'
import Blog from '#/components/Blog'
// Account components, loaded lazily
const AccountSettings = r =>
require.ensure([], () => r(require('#/components/AccountSettings')), 'accountComponents')
const ProfileSection = r =>
require.ensure([], () => r(require('#/components/account/Profile')), 'accountComponents')
const PlanSection = r =>
require.ensure([], () => r(require('#/components/account/Plan')), 'accountComponents')
const TeamSection = r =>
require.ensure([], () => r(require('#/components/account/Team')), 'accountComponents')
const IntegrationSection = r =>
require.ensure([], () => r(require('#/components/account/Integration')), 'accountComponents')
// App components loaded lazily, grouped by the 'appComponents' param
const MainApp = r =>
require.ensure([], () => r(require('#/components/MainApp')), 'appComponents')
const Default = r =>
require.ensure(
[],
() => r(require('#/components/App/Default')),
'appComponents'
)
const Search = r =>
require.ensure(
[],
() => r(require('#/components/App/Search')),
'appComponents'
)
const Templates = r =>
require.ensure(
[],
() => r(require('#/components/App/Templates')),
'appComponents'
)
const Lists = r =>
require.ensure(
[],
() => r(require('#/components/App/Lists')),
'appComponents'
)
const Outreach = r =>
require.ensure(
[],
() => r(require('#/components/App/Outreach')),
'appComponents'
)
import { Message } from 'element-ui'
Vue.use(Router)
export const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '*',
name: '404',
meta: { title: `Page not found` },
component: Error404
},
{
path: '/help',
name: 'Help',
meta: { title: `Help` },
component: Help
},
{
path: '/product',
name: 'Product',
meta: { title: `Product` },
component: Product
},
{
path: '/services',
name: 'Services',
meta: { title: `Services` },
component: Services
},
{
path: '/team',
name: 'Team',
component: Team
},
{
path: '/pricing',
name: 'Pricing',
meta: { title: `Pricing` },
component: Pricing
},
{
path: '/blog',
name: 'Blog',
meta: { title: `Blog` },
component: Blog
},
{
path: '/login',
name: 'Login',
meta: { title: `Login` },
component: Login
},
{
path: '/register',
name: 'Register',
meta: { title: `Register` },
component: Register
},
{
path: '/trial',
name: 'FreeTrial',
meta: { title: `Free trial` },
component: FreeTrial
},
{
path: '/viewlist/:id',
name: 'SharedList',
meta: { title: `View shared list` },
component: SharedList
},
{
path: '/app',
component: MainApp,
beforeEnter (from, to, next) {
if (store.getters.getUserStatus.loggedIn) {
next()
} else {
Message({
message: `You can't access the app because you're not logged in`,
type: 'error'
})
next({ name: 'Login' })
}
},
children: [
{
path: '/account',
component: AccountSettings,
beforeEnter (from, to, next) {
if (store.getters.getUserStatus.loggedIn) {
next()
} else {
Message({
message: `You can't access your profile because you're not logged in. Please log in again`,
type: 'error'
})
next({ name: 'Login' })
}
},
children: [
{
path: '',
name: 'ProfileSection',
meta: { title: `Edit profile` },
component: ProfileSection
},
{
path: 'plan',
name: 'PlanSection',
meta: { title: `Manage plan` },
component: PlanSection
},
{
path: 'team',
name: 'TeamSection',
meta: { title: `Manage team` },
component: TeamSection
},
{
path: 'integration',
name: 'IntegrationSection',
meta: { title: `Integration` },
component: IntegrationSection
}
]
},
{
path: '',
name: 'AppDefault',
meta: { title: `Explore saphire` },
component: Default
},
{
path: 'search',
name: 'AppSearch',
meta: { title: `Search influencers` },
component: Search
},
{
path: 'templates',
name: 'AppTemplates',
meta: { title: `Manage templates` },
component: Templates
},
{
path: 'lists',
name: 'AppLists',
meta: { title: `Manage lists` },
component: Lists
},
{
path: 'list/:id',
name: 'ListView',
meta: { title: `View list` },
component: ListView
},
{
path: 'outreach',
name: 'AppOutreach',
meta: { title: `Outreach` },
component: Outreach
}
]
}
]
})
router.beforeEach((to, from, next) => {
// Change title based on meta.title property
if (to.meta.title) {
document.title = `saphire | ${to.meta.title}`
} else {
document.title = `saphire`
}
// Checking if inside or outside app and assigning the result to global store variable
if (to.matched.length > 0) {
to.matched[0].path === '/app'
? store.commit('setAppState', true)
: store.commit('setAppState', false)
}
next()
})
export default router