0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MPAでuseRoute

Posted at

ここから先はミラーです。

MPA(マルチ・ページ・アプリケーション)でuseRouteを利用したくて、Vue Router のuseRouteライクなuseRouteを実装してみたので、紹介します。

初期実装

ブラウザからページのURLを取得し、正規表現を利用する等して、分解していました。
実装として綺麗ではなく、汎用性も低いので、コードは載せません。

Nano Stores + Nano Stores Router + Nano Stores Vue を利用した実装

Nano Stores

コンパクト(軽量)かつUIフレームワーク・ライブラリ非依存(Vue.js3/Vanila JS etcで利用可能)な状態管理ライブラリ

Nano Stores Router

Nano Stores用のルーティング・ライブラリ

Nano Stores Vue

Vue.jsからNano Store を利用しやくするためのライブラリ。

本題:ルータ部分

Nano Stores Router で実装。

router.ts
import { createRouter } from '@nanostores/router'

export const $router = createRouter(
  { frame: '/frames/:id' },
  { links: false }
)

Nano Stores Routerは(デフォルトで)リンク(aタグ)をトラッキングし画面遷移をNano Stores Routerでコントロールできるようにしていますが、MPAではこの挙動は不要なので、{ links: false } を設定して、リンクのトラッキングをオフにしています。

本題:useRoute 実装

use-route.ts
import { $router } from './router.ts'
import { useStore } from '@nanostores/vue'

export function useRoute() {
  const router = useStore($router)

  const params = router.value?.params

  const query = router.value?.search

  const path = router.value?.path

  return { params, query, path }
}

利用例

import { useRoute } from './use-route.ts'

const route = useRoute()
const id: string = route.params?.id ?? ''
const refStr: string = route.query?.ref ?? ''

最後に

Nano Stores はPiniaほど、Nano Stores RouterもVue Router ほど、多機能ではありませんが、コンパクト(軽量)なので、使いどころは多々?あるのではないか思います。
Nano Stores、調べてみては如何でしょうか?

PS: このuseRouteは自作Railsアプリ(レガシー版)のために実装しました。
https://github.com/asip/easel-legacy
https://qiita.com/asip2k25/items/8fd4a4d0f3ee515e0012

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?