I have a route/URL :
Ex. http://localhost:8080/qr-codes
I want to access to the first segment
qr-codes
How do I do that ?
I used to be able to do sth like this in Laravel
Request::segment(1);
CodePudding user response:
const getUrlPathSegments = () => (
(new URL(window.location.href)).pathname.split('/').filter(Boolean)
)
for example, when you call the function on current stackoverflow page, you get:
getUrlPathSegments() === ['questions', '70427242', 'vuejs-accessing-specific-url-segment']
getUrlPathSegments()[0] === 'questions'
CodePudding user response:
Using URL.pathname
and String#split
:
const str = 'http://localhost:8080/qr-codes';
const firstSegment = (new URL(str)).pathname.split('/')[1];
console.log(firstSegment);
Vue demo:
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>