简体   繁体   中英

What is the best way to grab first URL segment from Vue.js hash mode?

I have this URL generated by my vue.js app

http://localhost:8080/#/url-groups

I need to access url-groups

I've tried

const firstSegment = new URL(window.location.href).pathname.split('/#/')

I kept getting '/'


I've also tried:

const firstSegment = new URL(window.location.href).pathname.split('#'); console.log(firstSegment);
VM21687:1 ['/']


const firstSegment = new URL(window.location.href).pathname.split('/#/'); console.log(firstSegment);
VM21719:1 ['/']


const firstSegment = new URL(window.location.href).pathname.split('/'); console.log(firstSegment);
VM21751:1 (2) ['', '']

Can someone pls correct me?

Try out to get the hash segment then split using / as separator finally get the element of the splitted array:

const [,secondSegment] = new URL(window.location.href).hash.split('/')

or

const segment= new URL(window.location.href).hash.replace('#/','')

In case that's still relevant - you can use vue-router . Assuming you are using Vue 3 or the composition API, it would look like this:

import { useRoute } from 'vue-router';

const route = useRoute();
const firstSegment = route.path;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM