bencodezen / vue-enterprise-boilerplate

An ever-evolving, very opinionated architecture and dev environment for new Vue SPA projects using Vue CLI.
7.78k stars 1.32k forks source link

Handling URL paths and path generation functions #11

Closed jnarowski closed 6 years ago

jnarowski commented 6 years ago

This is an issue I've been toying with as my app grows. How to handle URL paths within the app. What I mean specifically, is building route paths, path helpers etc.

As my app grows, having to build all of my URL paths inline in the templates feels clunky. option 1: { name: 'site.page', params: { site_id: siteId, page_id: result.webpage_id }} option 2: "/sites/" + site.id + "/edit

Neither feel clean to me, to have in a template. If the params change or new ones are added, I have to go through and change all my templates, not to mention I need to get the name right. If I don't, and don't set it with strong dicipline in the router, the paths break.

My question is this, have you considered a path generation module, something that could be imported as needed, or perhaps as a plugin?

this.$paths.sitePath({ site_id }) OR import { sitePath } from '@/modules/paths' <router-link :to="sitePath({ site_id })

Obviously these all "work", but what's best as an application grows to thousands of routes.

chrisvfritz commented 6 years ago

I often consolidate stuff like that in a BaseLink component. For example, external links like this:

<BaseLink href="https://vuejs.org/">
  External link
</BaseLink>

Might automatically get attributes like target="_blank" added to them:

<a href="https://vuejs.org/" target="_blank">
  External link
</a>

And internal links (i.e. they have no href):

<BaseLink name="home" :params="siteParams">
  Internal link
</BaseLink>

Can pass on the appropriate props to router-link:

<router-link :to="{ name, params }">
  Internal link
</router-link>

When there's a specific kind of link, I can wrap BsaeLink in a new component:

<SpecialLink :site-id="siteId">
  Hello
</SpecialLink>

And internally, that component can use helpers to define the appropriate link given the context it can assume.

I like the idea of adding a BaseLink example to the app. 👍

jnarowski commented 6 years ago

Nice, that makes perfect sense. So BaseLink just wraps router-link and allows a slightly simpler synax? You're not hard coding any route paths but at least the base link is making the synax in templates a bit shorter and simpler!

Simple. Good call.

chrisvfritz commented 6 years ago

Yep, that's exactly it. 🙂

chrisvfritz commented 6 years ago

Just added a BaseLink component to resolve this. 🙂