What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code in app.js:

// VueRouter
import VueRouter from 'vue-router';
import routes from './routes.js';
Vue.use(VueRouter);

var router = new VueRouter({
    mode: 'history',
    routes
})

Below is a sample of my routes file:
let routes = [

    // General 
    { path: '/about', component: require('./components/Home/About.vue').default },
    { path: '/pasword-change',  component: require('./components/ChangePassword.vue').default },

    // User
    { path: '/User', component: require('./components/User/Dashboard.vue').default },


    // Modirator
    { path: '/Modirator', component: require('./components/Modirator/Dashboard.vue').default },

    // Editor
    { path: '/Editor', component: require('./components/Editor/Dashboard.vue').default },


    // Error
    { path: '*', component: require('./components/Errors/404.vue').default} },

]
export default routes
I want to authenticate the user roles after login by making an AJAX request to the backend. If the role is User, it should use (routes-user.js), if it's Moderator it should use (routes-mod.js), else it should use the general routes. I aim to hide the paths like /user, /moderator, /editor from the client. After login, each role should redirect to its respective component at the root URL (/). Thank you for your assistance.

Answer №1

In my recent experiment, I was able to successfully implement a solution similar to what you are looking for regarding normal component passing and lazy loading components in Vuex. The concept involved utilizing a variable named 'unauthorized' to dynamically load different components using either a javascript ternary operator or template strings.

import Vue from 'vue'
import Router from 'vue-router'
import Auth from './views/Auth.vue'
import Board from './views/Board.vue'

Vue.use(Router)

let unauthorized = true;

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/auth',
      name: 'authenticate',
      component: unauthorized ? Auth : Board
    },
    {
      path: '/',
      name: 'home',
      component: () => import(`./views/${unauthorized ? 'Auth.vue': 'Board.vue'}`)
    }
  ]
})

Detailed Explanation

Based on your specific requirements, one approach could be to store a variable ('access-type') in local storage indicating the user's role as 'moderator', 'user', or 'editor'. This variable can then be retrieved in the router.js file and leveraged with template strings to dynamically determine the component path.

If you require further assistance or clarification, feel free to reach out!

Answer №2

To overcome the issue, you can attach meta data to your routes and then validate this meta data before accessing a route:

    { path: '/about', component: require('./components/Home/About.vue').default },
    { path: '/pasword-change',  component: require('./components/ChangePassword.vue').default },

    // User
    { path: '/User', component: require('./components/User/Dashboard.vue').default, meta: {authorize: ["Admin"]} },

Include the following method in your router:

router.beforeEach((to, from, next) => {
  const { authorize } = to.meta
  // Retrieve currently logged-in user (in my case it's fetched from vuex)
  const currentUser = store.getters['authentication/user']

  if (!currentUser && to.path !== '/login') {
    // If not logged in, redirect to login page with return URL
    return next({ path: '/login', query: { returnUrl: to.path } })
  }

  if (authorize) {
    // Check if route is restricted by role
    if (authorize.length && !authorize.some(r => currentUser.roles.includes(r))) {
      // Role not authorized, so redirect to home page
      return next({ path: '/' })
    }
  }

  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

Using an array as an argument for .map() results in an error

This is quite unusual. Currently, I am passing an array containing a single object to the Render method of a React component: let content = this.state.links.map(link => { // eslint-disable-line return ( <li key={link._id}> <a href ...

I am struggling to render the pages and components in React while using BrowserRouter

Below is the code snippet for App.js and Home.js that I'm working on. My aim is to showcase the Home.js component in the browser. App.js import "./App.css"; import { Route, BrowserRouter } from "react-router-dom"; import Home from ...

Creating a dynamic JSON structure from an array list of elements: A step-by-step guide

I am faced with the task of transforming an array of employee IDs, listed as follows: empIds: [38670, 38671, 38672, 38673], into a JSON payload structured like this: { "members": [ { "EmployeeId": &quo ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

What are all the functionalities provided by jquery select?

Currently, I am venturing into testing out a new jQuery plugin. let myPlugin = new MyPlugin(); $(#myPlugin).someFunction(); console.log($(myPlugin)) I'm curious - is there a way for me to see a full list of the available functions/methods for me to ...

Utilize the withCredentials property in conjunction with $resource

I am looking to utilize a resource with a cookie set in the navigator. Using $http makes it simple, just need to set withCredentials to true: $http({ method: 'POST', url: url, data: user, withCredentials: true }); However, for ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

The AJAX form fails to submit the information, causing PHP to not process the request

I encountered an issue with this particular form a few days ago which was resolved using a different PHP code provided by the helpful folks here. However, after making a small change to the form, it no longer works. I have verified that all the variables b ...

The header and sub-navigation are in disarray and require some help

Dear web experts, After six months of learning to code websites, I'm tackling a big project with some challenges. The recent changes to the header and subnav have thrown everything off balance, making it look wonky and not quite right. Specifically, ...

Tips for navigating to a new route after a successful AJAX request

Hey everyone, I'm new to Vue and currently using version 2.5. I have been doing a lot of research online and came across this.$router.push('/login') for redirection, but it was not working for me. This has left me a bit confused on how to ac ...

Differences between React Router's createBrowserRouter and Browser RouterWhen it

As I embark on a fresh React endeavor, my goal is to incorporate the most up-to-date version of React Router. According to the documentation, createBrowserRouter is the preferred choice for web projects. While they mention that it allows for certain data A ...

What is the proper way to retrieve the Nuxt context within the fetch() hook?

Is there a way to access the props within an async fetch() function when also using async fetch(context)? I'm trying to figure out how to work with both simultaneously. ...

The Javascript logic on the NewForm for a Sharepoint 2013 on-premise list is failing to trigger

Screen shot linkThere seems to be an issue with the code I have written. The save button should only be enabled if all 5 checkboxes are ticked, but currently, the button is not disabled on form load. I have tried adding the code in both CEWP and SEWP, bu ...

Load Materialize autocomplete with data from a JSON file

After hours of research, I am struggling to populate my autocomplete input using the Materialize plugin for a website project. Since I am not well-versed in json or ajax, implementing the original example from the documentation with static data has been qu ...

Is it possible for memory leaks to occur due to the use of the JavaScript setInterval

Currently in the works on a JavaScript animation project that is showing promise. I've observed that using setInterval(), setTimeout(), and even requestAnimationFrame results in automatic memory allocation and frequent garbage collection. Too many GC ...

Steps for setting up single sign on in an Angular 2 application

Currently, I am working on a web application that has been developed using angular2. One of the requirements for this application is to incorporate a single sign-on feature, where users do not have to manually input their login credentials. Instead, the ap ...

Creating a link using curly braces {{ }} in VUE js

I need assistance in creating links to different pages using data in curly brackets {{ }}, I am having trouble figuring out the correct way to implement them. <div id="app"> <div v-for="data in categorie"> &l ...

How did my attempt to add a length() method to Object end up breaking jQuery?

Here is the code I created: Object.prototype.length = function(){ var count = -1; for(var i in this) count++; return count; } Surprisingly, when viewing my page with Firebug enabled, it gives an error stating that jQuery's .appendTo() is ...

The modal disappears when the user clicks on the Previous/Next buttons of the jQuery UI datepicker

Using the jQuery datepicker from https://jqueryui.com/datepicker/ along with the UIkit framework found at I'm trying to incorporate the datepicker within a form that is inside a modal window. The issue arises when the modal window disappears after i ...