技術っぽいことを書いてみるブログ

PythonとかVue.jsとか技術的なことについて書いていきます。

vue.js ~MPA(Multi Page Appliction)にした場合のクエリパラメータの取得について~

はじめに

前回の記事で、SPAじゃなくて、
MPAとしてVue.jsアプリケーションを構築する手順をまとめました。。。
で、構築していて、クエリパラメータって、どう取得するのか疑問に思ったので…
調べましたので、まとめておきます・・・。

やってみた

  • test.vue
<template>
  <div id="app">
    <span>TESTです。{{ param1 }} , {{ param2 }}</span>
    <br>
    <span>{{ locationSearch }} </span>
  </div>
</template>

<script>

export default {
  name: 'Other',
  data: function(){
    return {
      locationSearch: '',
      param1 : '',
      param2 : ''
    }
  },
  created() {
    this.locationSearch = window.location.search;
    const urlParams = new URLSearchParams(window.location.search);
    this.param1 = urlParams.get("param1");
    this.param2 = urlParams.get("param2");
  }
}
</script>

<style>
</style>

window.location.searchで、URLの?以降の文字列が取得できるので、
URLSearchParamsを使用して、パラメータをオブジェクト化して、キーを基に値を取得する

  • 実行結果
    http://localhost:8080/test?param1=hoge&param2=fugafugaで実行
    f:id:where-is-wally:20210805132235p:plain

最後に・・・

もうちょっと簡単な方法があるといいのですが…
調べているとVueRouterでの例がたくさん検索されるので、やっぱりSPAとして構築する方が一般的なのかなと思いました…。
どなたか、他によい方法があれば、ご教授ください・・・。