1

I would like to have different url(Consumer and Seller) for the same component SingleProduct, which the following codes works well:

const routes = [
  {
    path: "/:name",
    name: "SingleProductSeller",
    component: SingleProduct
  },
  {
    path: "/seller/:name",
    name: "SingleProductConsumer",
    component: SingleProduct,
  },
]

Instead of separating into two, is there any other method? For example, is it possible to make an alias with params like following and how to?

  {
    path: "/:name",
    name: "SingleProduct",
    component: SingleProduct,
    alias: "/seller/:name/",
    props: true,
  },

Thank you.

2
  • "is it possible to make an alias" 👈 yes ~ router.vuejs.org/guide/essentials/redirect-and-alias.html#alias Commented Mar 11, 2020 at 3:15
  • Thank you for your reply. Is alias with params (:name) allowed as well? As I read from somewhere else that it is not allowed. Commented Mar 11, 2020 at 4:40

1 Answer 1

1

You can use alias feature of the vue-router. It is nicely explained in the docs.

However, you should avoid this if possible since you are using dynamic path fragments and these are two different routes conceptually and so should be distinct routes even if they point to the same component. You will run into bookmarking problem - The page won't transition to the same route even since they are just aliases.

If you really want to avoid DRY, you should use simple function-based abstraction instead of relying on aliases:

function makeSingleProductRoute(name, path) {
    return {
        name, path,
        component: SingleProduct
        // Reusable guards if required.
    };
}


const router = new VueRouter({
    routes: [
        makeSingleProductRoute("SingleProductConsumer", "/seller/:name"),
        makeSingleProductRoute("SingleProductSeller", "/:name")
    ]
});
Sign up to request clarification or add additional context in comments.

4 Comments

IMO, I'd do the /seller route first as it has a more specific pattern to match. See router.vuejs.org/guide/essentials/…
@Phil, Indeed, you are right. Seller should come first.
Thank you for you reply. I have read the documents before and wondered if alias with params is allowed. As I read from somewhere else that alias with params is not supported for vue-router , and can't find additional information from the Vue website.
@Qness, Yes, that is right. Dynamic paths do not work with aliases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.