LoginSignup
19
18

More than 5 years have passed since last update.

vue-routerでページ遷移を検知して、GAのpageviewを送信する

Last updated at Posted at 2017-07-30

合同会社kumanoteのTanakaです。
vue-router使用時にページ遷移を検知して、Google AnalyticsのBeaconを飛ばす実装の紹介になります。

ページ遷移の検知

$routeという変数をwatchすることで、ページ遷移を検知することができます。

単一のrouter-viewを使っている場合は、一箇所実装することで
全てのページ遷移に反応して、処理を行うことができます。
(※ 複数のrouter-viewを使っている場合は別の作り込みが必要になります。)

具体的には以下のような感じになります。

<template>
  <router-view></router-view>
</template>

<script>
export default {
  watch: {
    '$route': function (to, from) {
      if (to.path !== from.path) {
        // ここに処理を追加します。
      }
    }
  }
}
</script>

GAの送信

こちらが参考になります。

ga('set', 'page', '/new-page.html');
ga('send', 'pageview');

みたいに送信するといいようです。

最終的には以下のような形になります。
(※ アプリの起動時にgaのライブラリ読み込みは前提になります。)

<template>
  <router-view></router-view>
</template>

<script>
export default {
  watch: {
    '$route': function (to, from) {
      if (to.path !== from.path) {
        window.ga('set', 'page', to.path);
        window.ga('send', 'pageview');
      }
    }
  }
}
</script>

以上になります。

19
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
18