Skip to content

Instantly share code, notes, and snippets.

@rafaelkendrik
Last active August 11, 2020 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelkendrik/cc4df973d7c7af947306f557765ea45b to your computer and use it in GitHub Desktop.
Save rafaelkendrik/cc4df973d7c7af947306f557765ea45b to your computer and use it in GitHub Desktop.
Get route from vue-router by href
// will return the route based on location
console.log(
VueRouter.prototype.resolve.call( // can be $router.resolve instead
this.$router,
'/my-path'
)
)
// or
const resolve = VueRouter.prototype.resolve.bind(this.$router)
console.log(resolve('my-path'))
// we can get the result .route
// cannot contain base url to location (2nd argument)
// final
function VueRouterResolve ($router) {
return $router.resolve.bind($router)
}
const vueRouterResolve = new VueRouterResolve(this.$router) // ideal to use "global" // can be singleton // should return a promise.
const { pathname } = new URL(href)
const to = vueRouterResolve(pathname)
// or
function getVueRouteByPathname (pathname, $router) { // ideal to use on guards (beforeEach, afterEach)
return $router.resolve.call($router, pathname)
}
function getVueRouteByHref (href, $router) {
return $router.resolve.call($router, (new URL(href)).pathname)
}
// or using path-to-regexp - do not depende of vue-router instance
// ideal to use before vue-router instance.
import { routes } from './router.js'
import { match } from 'path-to-regexp'
const routesWithMatcher = routes.map(route => ({
...route,
matcher: match(route.path)
})
const findRouteByPathname = pathname =>
routesWithMatcher.find(({ matcher }) => matcher(pathname))
const { pathname } = new URL(href)
const route = findRouteByPathname(pathname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment