1

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

xtreebug
  • 25
  • 8
  • What would be the use-case for such thing? – kissu Nov 28 '22 at 10:16
  • Hi, thanks for your answer so I tried to create some static pages based on the backend response which is an array, and I tried this way to make a dynamic route and I just add the content inside the template – xtreebug Nov 28 '22 at 10:20
  • You could have a dynamic component, where you're making the actual computation. Keep it in a `.vue` file, so that you benefit of all the tooling and the compilation step (not sure you can run that easily in a `.js` file). Especially since you don't have any specific benefit doing it in the router. Meanwhile, `/` doesn't seems to be a dynamic path. – kissu Nov 28 '22 at 10:24
  • This is a Nuxt2 example, but the idea would be similar in your case: https://stackoverflow.com/a/67490633/8816585 – kissu Nov 28 '22 at 10:24
  • @kissu so its not possible for me to do it like that? :( – xtreebug Nov 28 '22 at 10:28

1 Answers1

1

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.

kissu
  • 40,416
  • 14
  • 65
  • 133