Tengo una ruta/URL:
Ex. http://localhost:8080/qr-códigos
Quiero acceder al primer segmento
qr-codes
Cómo puedo hacer eso ?
Solía ser capaz de hacer algo como esto en Laravel
Solicitud::segmento(1);
const getUrlPathSegments = () => ( (new URL(window.location.href)).pathname.split('/').filter(Boolean) )por ejemplo, cuando llama a la función en la página actual de stackoverflow, obtiene:
getUrlPathSegments() === ['questions', '70427242', 'vuejs-accessing-specific-url-segment'] getUrlPathSegments()[0] === 'questions'Usando URL.pathname y String#split :
const str = 'http://localhost:8080/qr-codes'; const firstSegment = (new URL(str)).pathname.split('/')[1]; console.log(firstSegment);demostración de Vue:
new Vue({ el: "#app", computed: { path: function() { const firstSegment = (new URL(window.location.href)).pathname.split('/')[1]; return `${firstSegment}/create`; } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app">{{path}}</div>