Include a new route in the Vue.js router dynamically during runtime

I am in the process of developing an application and I want to incorporate extensions into it. These extensions will have their own Vue components, views, and routes. Instead of rebuilding the entire app, I am looking for a way to dynamically add these new views and routes using Vue 2.

Below, I have included the files that provide more clarity on this question. The router/index.js file contains the foundational structure and is included in the main.js file in the usual manner. When the app.vue loads, the new routes should be loaded and added to the existing ones.

router

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/test">Test</router-link>
    </div>
    <router-view/>
  </div>
</template>

<script>
// @ is an alias to /src
import TestView from '@/views/Test.vue'

export default {
  name: 'Home',
    components: {},
    created() {

      <add route to router>({
          component: TestView,
          name: "Test",
          path: "/test"
      })
    }
}
</script>

To illustrate how I want to add the route, I used the phrase <add route to router>. Once the route is added, users should be able to navigate directly to the new view using

<router-link to="/test">Test</router-link>
.

I would greatly appreciate any assistance with this matter.

Answer №1

Utilize addRoute function to dynamically add routes during runtime. Below is the explanation of this method as detailed in the official documentation:

Adds a new route to the router. If a route with the same name already exists, it will be replaced by the new one.

To use this feature, import the router into your App.vue file:

App.vue

<script>
import router from './router/index.js';
import TestView from '@/views/Test.vue'

export default {
  created() {
    router.addRoute({
      component: TestView,
      name: "Test",
      path: "/test"
    })
  }
}
</script>

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

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

Utilize jQuery to hide and then show elements based on text input

Recently, I came across a useful jQuery filter example that sparked my interest. To test it out, I created my live example and shared the code on CodePen (or you can check out the Fiddle if you prefer). One issue I encountered was that after entering text ...

I want to dynamically change the color of a text pill based on the word using the Vue composition API. How can I achieve this using a computed property?

I possess a pill shape that displays either Production or Development. My aim is to have the background color vary based on whether it pertains to production or development. I've successfully achieved this using the option api in the past, but I am en ...

Place the text within the contenteditable body of a frame at the specific caret position

Within my iframe object, there is a contenteditable body. I am trying to paste text or HTML elements at the caret position. However, when I attempted this code snippet, I encountered an error message saying Cannot read property 'createRange' of u ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

Steps to deactivate a JavaScript function once the page has undergone a Page.IsPostBack event

My current setup involves a simple div with the display set to none. Upon page load, I use $("#MyDiv").show(); to display the div after a delay, allowing users to enter information into the form and submit it using an asp.net button. After submitting the ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

Jquery cascading menu

I'm currently experiencing difficulties in creating dropdown menus using jquery and css. Below is my HTML code: <nav class="topNav"> <ul> <li> <a href="#menu" class="menu-toggle"><img src ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

Positioning Div at the Bottom of a Interactive Flip Card Using Bootstrap 4

My current project features a creative flip image card created using bootstrap and js. On the back of the card, there is a title, a main text body, and a few small additional pieces of information. My goal is to have these three small bits of information a ...

The attempt to fetch an additional 10 items through an AJAX call failed to meet expectations

I want to implement a feature where 10 items are loaded each time the "load more" button is clicked. Initially, I send the first 10 items and use dajaxice to load another set of 10 items everytime the button is pressed. Below is my view: def dj(request, ...

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...

Div keydown event not being triggered in Vue

I've been struggling to get my event to fire despite following the instructions in the title. @keydown="keyPressed($event)" Although currently it looks like this, I have also attempted setting the tabIndex and adding it on mount as shown be ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

When trying to integrate Angular.ts with Electron, an error message occurs: "SyntaxError: Cannot use import statement

Upon installing Electron on a new Angular app, I encountered an error when running electron. The app is written in TypeScript. The error message displayed was: import { enableProdMode } from '@angular/core'; ^^^^^^ SyntaxError: Cannot use impor ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Attempting to generate printed documents with multiple components spread across individual pages using react-to-print

I am working with the react-to-print library and I have a requirement to print a list of components, with each component on its own separate page. However, when I click on the print button, I encounter an error stating that the argument does not appear to ...

How can I incorporate images into my Vue Select dropdown?

Currently, I am using the vue-select component to display dropdowns on my website. These dropdowns are populated with data provided through the :options attribute. Specifically, I am working on implementing a credit card dropdown and would like to includ ...