Generating a Vue JS component on the fly

How can I dynamically create a component in Vue JS on click and then route to that component in a single click event? I am using Vue 3 and my current code snippet looks like this:

methods:{
  routerClick(value){
    console.log("The number is "+value)
    this.$router.push({path:'New', name:'New', component: ()=>Vue.component('New')})
  }
},

I specifically want to generate a new component within this method and then navigate to that component using the router. Any suggestions or solutions would be greatly appreciated.

Answer №1

Here is a straightforward approach that I found effective (I am not well-versed in Vue 3).

The key is to utilize the addRoute method before pushing to it, as you cannot specify the route component directly when pushing to a route.

You can view the solution in action on this codesandbox link.

 <template>
  <router-link to="/">Home</router-link>
  <button @click="createComponent">Create Component</button>

  <router-view></router-view>
</template>

<script>
import { getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
export default {
  name: "App",
  setup() {
    const app = getCurrentInstance().appContext.app;
    const router = useRouter();

    const createComponent = () => {
      // Check if the component has already been registered
      if (!app.component("NewComponent")) {
        app.component("NewComponent", {
          name: "NewComponent",
          template: `<div>This is a new component</div>`
        });
      }

      const newComponent = app.component("NewComponent");
      // Add a new route to the new component
      router.addRoute({ path: "/new", component: newComponent });

      router.push("/new");
    };
    return {
      createComponent,
    };
  },
};
</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

Exploring React and finding the way to a specific item

I have a list of users displayed in a table. When a user clicks on a row, I want to navigate to a different component to show the details. <tbody> {this.state.clients.map(client => ( <tr className="tableRow" onClick={() => this. ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

How to target and manipulate a specific element in the DOM using VueJS

One thing that puzzles me is how to efficiently select a specific element in the DOM using VueJS, with or without jQuery. Within my component, I've created a method function that performs the following task: $(".u-loc input").focusin(function() { ...

:root variables not being recognized in SCSS and Vue3 with Vite

I am encountering an issue with setting variables in my root SCSS file, as they are not being recognized correctly. Within my Vite configuration, I have included the following to import my styling: css: { preprocessorOptions: { scss: { additio ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

Ways to alter the path of a vuejs page according to a value saved in vuex?

I have saved the variable companyName in my Vuex store. I want to dynamically change the default loading page specified in the router.js file based on its value. component: function () { return (store.state.user.companyName ? import("A ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Troubleshooting: Resolving the "npm ERR! missing script: start" Issue

I'm encountering the error below: npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\..\AppData\Roaming\npm-cache\_logs\2019-04-27T18_02_39_6 60Z-debug.log Th ...

Building a custom error page with Laravel 10, Inertia JS, and Vue.js featuring resource routing

I recently embarked on a new project using Laravel 10, InertiaJS, and Vue3. As part of this project, I created two simple models: Blog and Listings. Although I followed a tutorial to set up the blog, I encountered some difficulties with the listings. While ...

What is the best way to access the local Express server that is located in the same directory as the frontend project

This is the structure of my project - backend > node_modules > .env package-lock.json package.json server.js frontend > index.html style.css script.js server.js import dotenv from 'dotenv'; dotenv.config(); import express from &apo ...

How do I specify a unique directory for pages in Next.js that is not within the src or root folders?

I'm currently facing an issue when trying to set a custom directory in Next JS. Although the default setup dictates that the pages directory should be located at the root or within the src directory, this arrangement doesn't fit my requirements ...

How to customize a dropdown menu with the size property?

Can anyone help me with styling a select box that uses the size attribute? Most tutorials only cover single-item select boxes. Has anyone dealt with styling select boxes with the size attribute before? Here's an example of what I'm trying to acc ...

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

Why does the child Vuex Store Object return undefined while the parent returns correctly?

I've come across some similar inquiries, but none quite fit my specific scenario. Upon logging this.$store.state.account, the expected results are displayed {__ob__: Nt} user: Object favorites_playlist: (...) firebaseI ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

Error message: Unhandled error: The function Role.Create is not defined

I'm encountering an issue with a ".create is not a function" error while trying to repopulate my database upon restarting nodemon. Previously, everything was functioning well and all the tables were populated successfully. However, I keep receiving th ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...