簡體   English   中英

從 Vue.js hash 模式獲取第一個 URL 段的最佳方法是什么?

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

我有這個 URL 由我的 vue.js 應用生成

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

我需要訪問url-groups

我試過了

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

我一直得到'/'


我也試過:

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) ['', '']

有人可以糾正我嗎?

嘗試獲取 hash 段,然后使用/作為分隔符進行拆分,最后得到拆分數組的元素:

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

或者

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

如果這仍然相關 - 你可以使用vue-router 假設您使用的是 Vue 3 或組合 API,它看起來像這樣:

import { useRoute } from 'vue-router';

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM