Display a 404 page on Vue router when the ID does not match

When it comes to displaying a 404 page if a parameter doesn't match, I'm a bit puzzled. For instance, if the user name is “joe” and someone tries to access “/joe/categories”, then the categories component should be displayed. Now, I want to implement a guard that redirects to a 404 component if someone attempts to access something like “/james/categories”. However, I'm not entirely sure what I need to fix here. The error message I received was "Unexpected error when starting the router: Error: Missing required param 'catchAll'"

const routes = [
  
  {
    path: '/:userName/categories',
    name: 'Categories',
    component: () => import(/* webpackChunkName: "home" */'@/views/Categories'),
    props: true
  },
  {
    path: '/:userName/products',
    name: 'Products',
    component: () => import(/* webpackChunkName: "home" */'@/views/Products'),
    props: true
  },
  {
    path: '/:userName/settings',
    name: 'Settings',
    component: () => import(/* webpackChunkName: "home" */'@/views/Settings'),
    props: true
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */'@/views/Login')
  },
  {
    path: '/registration',
    name: 'Registration',
    component: () => import(/* webpackChunkName: "registration" */'@/views/Registration')
  },
  {
    path: '/:catchAll(.*)',
    name: '404',
    component: () => import(/* webpackChunkName: "404" */'@/views/404')
  }
]

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters[‘users/isAuthenticated’]
  
  if (!isAuthenticated && to.name !== ‘Login’ && to.name !== ‘Registration’ && to.name !== ‘404’) {
    next({
      name: ‘Login’
    })
  } else if (isAuthenticated && store.getters[‘users/getUserName’] !== to.params.userName) {
    next({
      name: ‘404’
    })
  } else {
    next()
  }
})

Answer №1

Here is a solution that might work for you:

const routes = [

  {
    path: '/dashboard/:userName/categories',
    name: 'Categories',
    component: () => import(/* webpackChunkName: "home" */'@/views/Categories'),
    props: true
  },
  {
    path: '/dashboard/:userName/products',
    name: 'Products',
    component: () => import(/* webpackChunkName: "home" */'@/views/Products'),
    props: true
  },
  {
    path: '/dashboard/:userName/settings',
    name: 'Settings',
    component: () => import(/* webpackChunkName: "home" */'@/views/Settings'),
    props: true
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */'@/views/Login')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "registration" */'@/views/Register')
  },
  {
    path: '*',
    name: 'PageNotFound',
    component: () => import(/* webpackChunkName: "404" */'@/views/PageNotFound')
  }
]

router.beforeEach((to, from, next) => {
  const isLoggedIn = store.getters['auth/isLoggedIn']

  if (!isLoggedIn && to.name !== 'Login' && to.name !== 'Register' && to.name !== 'PageNotFound') {
    next({
      name: 'Login'
    })
  } else if (isLoggedIn && store.getters['auth/getUserName'] !== to.params.userName) {
    next({
      name: 'PageNotFound'
    })
  } else {
    next()
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently displaying a computed property on a template using Vuetify?

I am attempting to display only the initials of a user who is logged in while inside a store. Here is my template: <v-menu v-if="this.$store.getters.getLoggedUser"> <template v-slot:activator="{ on, attrs, userInitials }&quo ...

Vue Page fails to scroll down upon loading

I am facing a challenge with getting the page to automatically scroll down to the latest message upon loading. The function works perfectly when a new message is sent, as it scrolls down to the latest message instantly after sending. I've experimented ...

How can I assign a distinct identifier to individual instances of Vue.js components?

I am looking to build a Vue.js component that includes a label and an input. Here is an example of the structure I have in mind: <label for="inputId">Label text</label> <input id="inputId" type="text" /> Is ...

After a complete page refresh, Vue.js route parameters are not retained

When passing a user id from the router-link using params to display the user's detail on the profile page, everything works correctly. However, upon reloading the page, $route.params.id changes to undefined and the displayed data disappears. To retrie ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Using a HTML tag within vue js

Is it possible to dynamically change a <p> tag inside my component to be an <h1> tag based on a prop? If so, how can this be achieved? <template> <p>Hello world</p> </template> ...

What is the best way to set up an anchor element to execute a JavaScript function when clicked on the left, but open a new page when clicked in

One feature I've come across on certain websites, like the Jira site, is quite interesting. For instance, if we take a look at the timeline page with the following URL - When you click on the name of an issue (which is an anchor element), it triggers ...

Discovering the Secrets of Laravel 5: Harnessing the Power of Vue.js to Access Data Attribute Values

I'm a beginner in vue js. Within our app, we have implemented validation to check if a value already exists in the database. I would like to enhance this feature by making it dynamic. To achieve this, I have added a data attribute to my field which is ...

Each time I invoke the setInterval function, my counter speeds up - using vuejs

In my development process, I am creating a countdown that is triggered by a function. The main objective is to reset the countdown each time a user answers a question in the game and a new question appears. However, I have encountered a challenge where i ...

Creating a versatile tabbed interface with Vue.js for multiple uses

I am currently working on integrating a tabbed reusable component in vueJs, but I encountered an issue stating that a specific component is not defined. Below, you will find the code snippets for both components: //TabComponent <template> <di ...

Transitioning from Laravel blade to Vue.js: Managing tag handling techniques

Currently, I am working on a Laravel application that utilizes blade templates. My goal is to gradually transition these templates into Vue.js, so for a period of time, I plan to use both Blade and Vue.js in my code simultaneously until the full migration ...

The process of downloading an image from Spring Boot using VueJs and displaying it within an <img> tag

I have created a Spring Boot backend with a Vue frontend. I am having issues when trying to download and display an image from Google Cloud Storage in my application. Sometimes the downloaded image appears to be cut off, as if not all bytes were sent. Howe ...

Tips for preventing the need to re-render every child component generated by the v-for directive

Here is a paragraph about the list of child components: <question-list-item v-for="(item, index) in questionListParsed" :key="item.id" :both-question="item" :class-id="classId" ...

Vue-good-table does not show the "empty state" once it has been populated with data

I am facing an issue with my vue-good-table where it does not re-render to display the "emptystate" message when I set the rows field to an empty array. Initially, it shows the message before I assign values into the rows field and then correctly displays ...

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

Error encountered when deploying mixed content

Currently working on a project and looking to deploy my dev server to firebase hosting. Encountered some Mixed Content errors in Chrome dev tools after deploying the app, indicating that I needed to switch certain source files from http to https. The erro ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...