1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VitePressでRouterの変更を検知する

Last updated at Posted at 2021-05-12

したいこと

VitePressでGoogle AnalyticsをしたいけどSPAだからページ移動しても検知してくれない。
なのでVitePressでRouterの変更を検知して検知させたい。

2021年6月追記

VitePressはビルド時サーバー側でもレンダリングを行うので
gtagがないよと怒られてしまう。
解決策としてはglobalThisを使って判断する

結論

.viteperss/theme/index.js
import DefaultTheme from 'vitepress/theme';
import { watch } from 'vue';

export default {
	...DefaultTheme,
	enhanceApp({ app, router }) {
		if (globalThis && globalThis.gtag) watch(router.route, () => {
			// 変更を検知したタイミングで呼んでくれる
		});
	}
}

解説

router.routereactiveなのでVue3のwatchを使って検知するだけです

【おまけ】Google Analyticsに対応させる

今回はgtagを利用します

.viteperss/theme/index.js
import DefaultTheme from 'vitepress/theme';
import { watch } from 'vue';

export default {
	...DefaultTheme,
	enhanceApp({ app, router }) {
		if (globalThis && globalThis.gtag) watch(router.route, () => {
			gtag('config', window.GA_MEASUREMENT_ID, {'page_path': router.route.path });
		});
	}
}
.viteperss/config.js
module.exports = {
	// 中略
	head: [
		// ここは各自scriptのURLに置きかえる
		[ 'script', { src: '', async: true } ],
		[ 'script', {}, `window.GA_MEASUREMENT_ID = 'Google analyticsに書いてあるIDを書く';window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());`]
	]
	// 中略
}

これでヨシ!
誤字などありましたら教えてください~

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?