Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there a way to create a vue 3 component directly in the route using a template?

I’m curious and want to try it, can I make a route in vue 3, where the component I made directly here is like this?

const sampleComponent = {
  template: `<section class='px-container py-20'>test</section>`
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;
    else return { top: 0 };
  },
  routes: [
    {
      path: "/",
      name: "homepage",
      component: sampleComponent
    }
  ]
});

Because if I try to like this, it can’t produce anything on my screen. maybe you guys can help me explain it, Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Even if that would be possible, why would you do that?
A .js file is "less powerful" than a .vue one.
No direct benefit trying to compile, export or hack the router.

The usual practice is to use components, they are meant for such task.
No need to be creative here, follow the common API practices established by Vue.

Again, it may be feasible (could be hacked somehow I guess) but I don’t see how you would use Composition API, {{ }} syntax or anything like v-for in a .js file.

A .vue file is plenty flexible and will allow you to achieve exactly the same but in a Vue context.


I’m just trying to make your life easier in the long run by not using something too complicated from the beginning.
If you have a very specific and advanced reason to do that compilation in the router despite the conventions and separation of concerns, you could look for that one on vue-router Github’s issues or ask the question on Vue’s discord.
But if you’re beginning with Vue, follow the conventions.


Also, if you want something highly dynamic regarding your template, Vue does have render functions (with JSX too). Plenty of flexibility.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading