How to create a route URL? #2616
|
Hello, I'm looking for a way to programmatically create a full URL in order to show a QR code. For example, I'm on the route |
Replies: 2 comments 3 replies
|
For now, I have to do const route = useRoute('/talks/[talkId]/get-started')
const url = computed(() => {
const baseUrl = window.location.origin
return `${baseUrl}/talks/${route.params.talkId}/overview`
})but it's not type safe. |
|
Use For example, with a named route: import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute('/talks/[talkId]/get-started')
const router = useRouter()
const url = computed(() => {
const { href } = router.resolve({
name: '/talks/[talkId]/overview',
params: { talkId: route.params.talkId },
})
return new URL(href, window.location.origin).href
})
If your route has an explicit const { href } = router.resolve({
name: 'talk-overview',
params: { talkId: route.params.talkId },
})That keeps param encoding and route changes in Vue Router instead of manually concatenating strings. |
Use
router.resolve()for this. It is the API Vue Router uses to turn a route location object into the final URL/href without navigating.For example, with a named route:
router.resolve()gives you the path that Vue Router would use for a<RouterLink>, including the router base if you configured one.new URL(href, window.loc…