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>