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

Variable missing in the ExpressJs view

Hey there! I'm new to Nodejs and currently experimenting with it. I've been trying to convert some of my basic Python codes to JavaScript. In one of my projects, I am sending a get request to the YouTube API and receiving 50 results in JSON forma ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

Adding HTML to a Vue instantsearch widget

I need assistance with converting a numerical value representing product ratings in a Vue instantsearch component into images of stars and half stars. Here is the code I have so far: <template> <ais-instant-search :search-client="searc ...

A promise is given when a value triggers a function

Having a problem with my code in the second function. When I log inside the function, it works fine. But when I assign a variable and call the function, it returns a pending promise instead of true or false. const mongoose = require('mongoose') c ...

Whenever the ajax oncomplete event is triggered, Primefaces overrides the functionality of jquery, leading to

I have implemented a plugin for fixed table columns in my Primefaces project. The plugin is somewhat functional, but I am facing some issues. primefaces v6.1 jQuery v1.7.1 It works under the following conditions; p:dataTable with <p:ajax event="page ...

Auto-populate AngularJS form using PHP array via JSON and $http

I came across a fantastic autocomplete feature in this plunker that I need to replicate using a PHP array with $http. When I tried adding an alert to check my array, it worked perfectly. However, I'm stuck on how to implement the filter in AngularJS. ...

The $routeChangeSuccess event is failing to trigger in ngNewRouter in AngularJS version 1.4

Transitioning from AngularJS 1.3 to AngularJS 1.4 has brought about some changes, including the use of AngularJS's new route method known as ngNewRouter, specifically introduced in AngularJS 1.4. Below is a snippet of my code: var versionModule = ng ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Highcharts - Troubleshooting the chart reflow feature

Take a look at the fiddle I created. I encountered an issue with the chart width when toggling the sidebar. After seeking help on Stack Overflow from this post, I was able to solve it. Now, I'm facing another bug where adding transitions while togg ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more. ...

Creating a clone of JSON for use as a template

I am working with a json template that I fill with product data. Here is an example of the json structure: // product template $scope.productAttributes = { "Code": null, 'Attributes': {} }; When a user inputs produ ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Tips for altering the entire page layout in Vuetify

For my project layout update, I am looking to switch the color scheme. layout/default.vue <v-app> .... </v-ap> I attempted to change the v-app color using this code, but it did not work: <v-app color="secondary" ...