LoginSignup
0
0

僕なりの vue-router 備忘録

Posted at

基本

コンポーネントとビューの違い

ビューは画面を構成するコンポーネント。URL によってページの切り替えをして表示非表示するコンポーネント

コンポーネントはページの中で使われる部品とかを指す。

記述方法

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>

<router-view></router-view>
 
<!-- Vue の読み込み -->
<script src="//unpkg.com/vue@3"></script>
<!-- Vue Router の読み込み -->
<script src="//unpkg.com/vue-router@4"></script>
 
<script>
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
]

const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(), // historyオプションを指定(ここでは hashhistory を使用)
  routes, // routes オプションを指定(routes: routes の短縮表記)
})

const app = Vue.createApp({})
app.use(router)
app.mount('#app')
</script>

ディレクトリ構成

my-router-project //プロジェクトのディレクトリ
├── index.html  //表示用フィル
├── node_modules
├── package-lock.json
├── package.json
├── public
│   └── favicon.ico
├── src
│   ├── App.vue  // メインコンポーネント(Root Component) レンダリングの起点
│   ├── assets
│   │   ├── base.css
│   │   ├── logo.svg
│   │   └── main.css
│   ├── components  // ページで利用するコンポーネントのディレクトリ
│   │   ├── HelloWorld.vue
│   │   ├── TheWelcome.vue
│   │   ├── WelcomeItem.vue
│   │   └── icons
│   ├── main.js  //エントリポイント(ルーターの有効化)
│   ├── router
│   │   └── index.js  //ルーティングの定義とルーターの生成
│   └── views  //ページを構成するコンポーネント(Route Components)のディレクトリ
│       ├── AboutView.vue  // About ページのコンポーネント
│       └── HomeView.vue  // Home ページのコンポーネント
└── vite.config.js  //Vite の設定ファイル

props を落とす

// /src/routes/index.js

{
    path: '/user/:uid',
        name: 'user',
            component: () => import('../views/UserSingleView.vue'),
                props: true  //props オプションを追加
},
<script setup>
const props = defineProps(['id']);
fetchPost(props.id)
</script>
 
<template>
    <PostComments :post-id="id" />
</template>

コンポーネントの動的インポート

component: () => import('../views/AboutView.vue')

普通にインポートするパターンと比べて初回アクセス時のダウンロードサイズが減少するから適宜使う。

プロパティの監視

同じコンポーネントで params で動的にプロパティを変更する場合は、結局監視しないといけない。

// watchを使って監視
watch(
    route,
    (to) => {
        userId = parseInt(to.params.uid);
        fetchUser(targetUrl + userId);
    }
)

// CompositionAPI の場合は onBeforeRouteUpdate というナビゲーションガードを利用できる
import { useRoute, onBeforeRouteUpdate } from 'vue-router';

onBeforeRouteUpdate( async (to) => {
  userId =  parseInt(to.params.uid);
  fetchUser(targetUrl + userId);
});

not found の設定

// /src/routes/index.js

{
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("../views/NotFoundView.vue"),
  },
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