Home > Net >  How to get url query parameters without Vue router?
How to get url query parameters without Vue router?

Time:12-05

I don't need routing for my Vue app so I didn't add the Vue router package to my project.

Given the following sample code for the App.vue

<script setup lang="ts">
import { onMounted } from "vue";

onMounted(() => {
  const routeHashContent = window.location.hash.substring(1);
  const hashParameters = new URLSearchParams(routeHashContent);

  const hashParameter = hashParameters.get("foo");

  if (hashParameter === null) {
    console.log("not found.");

    return;
  }

  console.log(hashParameter);
});
</script>

<template />

I could call the app with the url

http://localhost:5173/#?foo=bar

to make it work. Is there a way to get rid of the hash? The url might look like so

http://localhost:5173?foo=bar

Which code should I use instead of const routeHashContent = window.location.hash.substring(1); to get the queries?

CodePudding user response:

You can create an URL object by using

const url = new URL(window.location)

This object contains the url search parameters as the variable searchParams.

Access the params like this.

const bar = url.searchParams.get('foo')

CodePudding user response:

URLSearchParams is a good way to do this-

const urlParams = new URLSearchParams(window.location.search);

const param1 = urlParams.get("token")

// Output will be null if there is no query param of named "token"
console.log(param1);

But if you are not using a full URL or using a custom URL to parse params from then you need to create a URL object first of that custom URL and apply search on it. Why? read here.

// Non window URL, then need to create URL object
const queryURL = new URL("https://example.com/over/there?name=ferret&age=11");

// Then apply search on newly created object
const urlParams = new URLSearchParams(queryURL.search);

// Now, console the params,
console.log(urlParams.get("name"), urlParams.get("age"));

  • Related