名前付きルート
公式 Web サイトの一節を引用するには:
パスに加えて、ルートの名前も指定できます。これには次のような利点があります。
- ハードコードされた URL はありません
- パラメータの自動エンコード/デコード。
- URL のタイプミスを防ぎます。
- パスの並べ替えをバイパスします (表示 1 と同様)
改訂src/router/index.js
// src/router/index.js
const routes = [
{
// path 定义为restful 风格
path: '/user/:username',
name: 'user',
component: User,
},
]
App.vue
名前付きルートのアクセスを変更する
// 注意这里需要将 to => :to,需要动态绑定
// name 为 src/router/index.js 定义的路由名称
// params 为 restful 风格传参,参数存放的地方 (在路由传参再说)
<router-link :to="{name:'user', params:{username: 'zs'}">go to about</router-link>
公式文書に記載されている利点によると、
- 名前付きルートを使用した後、パスが変更された場合、
src/router/index.js
パス内のパスのみを変更する必要があり、ラベル内の値を変更する必要はありません。 - URL スプライシングを使用してパラメーターを渡す場合、URL を手動でエンコードおよびデコードする必要があります。params を介してパラメーターを渡すと、内部で処理するのに役立ちます。
- 3番目の点については話しません
- 例えば:
// 例如 restful 风格下
// 访问链接为 http://127.0.0.1:5173/#/user/zs
<router-link :to="{name:'user', params:{username: 'zs'}">go to about</router-link>
// 访问链接为 http://127.0.0.1:5173/#/user/ls
<router-link :to="{name:'user', params:{username: 'ls'}">go to about</router-link>
// 两个url 指向的是同一个地址,只是usename不一样
ネストされたルート
上に示したように、現時点ではネストされたルーティングを使用できます。
改訂src/router/index.js
// src/router/index.js
const routes = [
{
path: '/parent',
name: 'Parent',
component: Parent,
children:[
{
path: '/childrenA',
name: 'ChildrenA',
component: ChildrenA,
},
{
path: '/childrenB',
name: 'ChildrenB',
component: ChildrenB,
},
]
},
]
App.vue
Parent.vue
名前付きルートのアクセスを変更する
// App.vue
<template>
<router-link to="/parent>go to Parent</router-link>
<router-view></router-view>
</template>
// Parent.vue
<template>
<div>
<router-link to="/childrenA">childrenA</router-link>
<router-link to="/childrenB">childrenB</router-link>
<router-view></router-view>
</div>
</template>
最初にルートパスにアクセスしhttp://127.0.0.1:5173/
、次にhttp://127.0.0.1:5173/#/parent
最後の訪問にアクセスしますhttp://127.0.0.1:5173/#/childrenA
。これが実際には親ビューであり、そこに表示されているビューはネスト内のサブビューであることをhttp://127.0.0.1:5173/#/childrenB
発見した人はいますApp.vue
か?しかし、ルーターには反映されていません
名前付きビュー
公式ドキュメント引用:
入れ子表示ではなく、複数のビューを同時に(同じレベルで)表示したい場合があります。たとえば、サイドバー(サイドナビゲーション)とメイン(メインコンテンツ)の2つのビューを持つレイアウトを作成します。名前付きビューが送信されるので便利です。インターフェイスには、単一のアウトレットではなく、個別に名前を付けた複数のビューを含めることができます。router-view が名前を設定しない場合は、デフォルトのデフォルトが使用されます。
上図の head、content、foot がそれぞれ独立している場合は、この時点で名前付きビューを使用できます。
上のコード:
設定src/router/index.js
const routes = [
{
path: '/parent',
components: {
default: Content, 'head': Head, 'foot': Foot }
},
{
path: '/:path(.*)', component: NotFound },
]
// App.vue
<template>
<div style="height: 60px; background-color: aqua;">
<router-view name="head"></router-view>
</div>
<div style="height: 60px; background-color: aquamarine;">
<router-view style="height:500px"></router-view>
</div>
<div style="height: 60px;background-color: bisque;">
<router-view style="height:80px" name="foot"></router-view>
</div>
</template>
表示効果は次のとおりです。