2

With the vue-router (4) I have the following setup

import { createApp } from 'vue'
import App from './App.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './methods/routes.js'
import Notifications from '@kyvg/vue3-notification';
import vueTheStorages from 'vue-the-storages';
import * as Sentry from "@sentry/vue";
import { Integrations } from "@sentry/tracing";

const router = createRouter({
    history: createWebHashHistory(),
    base: '/dist/localhost',
    routes: routes.get_routes(),
})

const app = createApp(App);

app.use(router);

The issue comes when I have a link like

<router-link :to="{name: 'events.dashboard', params: { event_id: event.id, date_id: 'next' }} ">
    {{event.title}}
</router-link>

This creates a link

<a href="#/event/2668/next">Event</a>

Which is great, but if you right click the link and select open in new tab it goes to https://example.com/#/event/2668/next and I need it to go to https://example.com/dashboard/#/event/2668/next

It feels like there should be a setting in createRouter, but I can't find it in the docs

Mark
  • 70
  • 3
  • 13

1 Answers1

0

To set the base URL correctly, you can use the createWebHashHistory() function within createRouter(). However, you need to specify the base path where you want the # symbol to appear.

Here's an example of how to use it:

// at https://example.com/folder
createWebHashHistory() // gives a URL of `https://example.com/folder#`
createWebHashHistory('/folder/') // gives a URL of `https://example.com/folder/#`
// if the `#` is provided in the base, it won't be added by `createWebHashHistory`
createWebHashHistory('/folder/#/app/') // gives a URL of `https://example.com/folder/#/app/`
// you should avoid doing this because it changes the original URL and breaks copying urls
createWebHashHistory('/other-folder/') // gives a URL of `https://example.com/other-folder/#`

Important note: When running "as html", the above approach won't work:

// at file:///usr/etc/folder/index.html
// for locations with no `host`, the base is ignored
createWebHashHistory('/iAmIgnored') // gives a URL of `file:///usr/etc/folder/index.html#`

In your specific code, you can modify it as follows:

const router = createRouter({
    history: createWebHashHistory('/subfolder'), // gives a URL of `http://localhost:1234/subfolder/#` instead of original `http://localhost:1234/#`,
    // base: '/subfolder', // don't need it
    routes: routes.get_routes(),
})

If you need a different base URL in DEV mode and PROD mode, you can conditionally declare it using an example like this:

const router = createRouter({
    history: createWebHashHistory(import.meta.env.DEV ? '/' : '/subfolder'), // gives a URL of `http://example.com/subfolder/#` on PROD mode, and gives a `http://localhost:1234/#` on DEV mode
    // base: '/subfolder', // don't need it
    routes: routes.get_routes(),
})
rozsazoltan
  • 2,831
  • 2
  • 7
  • 20