Vue の記事.02-routing Vue Router

1 はじめに

Vue Router は、Vue.jsの公式ルーターです。Vue.js コアと深く統合されているため、Vue.js を使用して単一ページのアプリケーションを簡単に構築できます。ルーティングを使用すると、更新された部分のみが更新され、ページ全体は更新されません。

2. 基本的な使い方

(1)ラベル

  • <router-link to=""></router-link> リンク コンポーネント。標準のリンクとして表示される、URL に対応するコンポーネントを表示します。

  • <router-view></router-view> プレースホルダー、ルーティング コンポーネントを表示します <RouterView>

        <ul>
            <!--使用 router-link 组件进行导航  通过传递 `to` 来指定链接  `<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
            <router-link to="/a"><li>AAA</li></router-link>
            <router-link to="/b"><li>BBB</li></router-link>
            <!-- 动态参数 -->
            <router-link to="/c/1001"><li>CCC</li></router-link>
            <router-link to="/d"><li>DDD</li></router-link>
            <router-link to="/e"><li>EEE</li></router-link>
        </ul>
         
          <!-- 命名视图 -->
         <!-- 同级展示 展示多个路由组件, 通过 name命名路由 占位   -->
         <router-view name="A" class="left"></router-view>
         <router-view ></router-view>
         <router-view name="B" class="right"></router-view>

(2) ルータの定義

import {createRouter,createWebHistory} from 'vue-router'
import A from '../components/A.vue'
import B1 from '../components/B1.vue'
import B from '../components/B.vue'
import C from '../components/C.vue'
import D from '../components/D.vue'
import E from '../components/E.vue'
import NOTFOUND from '../components/NOTFOUND.vue'
// 定义路由
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [{
            path: '/a', //路径
            name: 'A', //命名路由
            component: A, //路由对应的组件
            alias: '/A', //别名
            // redirect: '/b',   // 重定向  当地址栏访问/a时,会自动定向到/b
            // redirect: { name: 'B1'},
        },{
            //  参数匹配   /:id 接收参数  可通过this.route.params.id访问参数
            path: '/c/:id',
            component: C,
            props: true, // 将props(访问参数)传递给路由组件
        },{
            path: '/b',
            name: 'B',
            component: B,
            children: [{ // 嵌套路由, 子路由
                path: 'b1',
                name: 'B1',
                component: B1
            }],
        },{
            // 参数正在匹配   :path为变量      
            path: '/:path(.*)*', //当匹配不到路由时, 跳转404 (只会在所有路由都匹配过后才会匹配)
            name: 'NOTFOUND',
            component: NOTFOUND
        },{
            // path: '/d/:uname+',    // 可匹配的路径   /d/uname1/uname2...
            path: '/d/:uname*', // 可匹配的路径    /d/ 及  /d/uname1/uname2...
            name: 'D',
            component: D,
        },{
            // 实现一个组件中展示多个路由视图
            path: '/e',
            name: 'E',
            components: {
                default: E, //默认展示
                A,
                B
            },
        }]
})
export default router

(3) ヒストリーモード

履歴属性:

  • ハッシュ モード: createWebHashHistory()。内部的に渡される実際の URL の前にハッシュ文字 (#) を使用します。URL のこの部分はサーバーに送信されないため、サーバー レベルで特別な処理を行う必要はありません。例: 127.0.0.1:xxxx/#/b/b1

  • HTML5 モード

(4) $routeと$router

this.$route 現在アクティブなルート オブジェクト (オプションの API)

$router Vue インスタンスでは、$router を通じてルーティング インスタンスにアクセスできます。

        <!-- 注册路由中通过  /:id 接收参数  可通过 当前活跃的路由对象 $route.params (参数对象)或 this.route.params.id访问参数  -->
        {
    
    { $route.params }}   
        {
    
    { this.$route.params.id }}

(5) プログラムによるナビゲーション

<template>
    <button @click="goto">跳转到A</button>
    <button @click="update">刷新页面</button>
</template>
<script>
    export default{
        methods:{
            goto(){
           //  $router  在Vue 实例中,  访问路由实例
        //  在该组件中, push()会在浏览器history这个产生记录,  可在浏览器前进后退中访问到,   replace不会
                this.$router.push({
                    name: 'A',    //命名路由
                    params: { id: 111 },
                    replace: true    ,// 在浏览器中不产生历史
                })
            },
            // 横跨历史
            update(){
                // forward()/back()/go()
                this.$router.go(0)
            }    
        }
    }
</script>

(6) パスルーティングパラメータ

パラメーター props: true; を使用してルートを定義する場合。

コンポーネントのルートパラメータとまったく同じプロパティ名を追加します。例: props: ['id'],

(7) ルーティングの遅延ロード

パッケージでアプリを構築する場合、JavaScript バンドルが非常に大きくなり、ページの読み込みに影響を与える可能性があります。異なるルートに対応するコンポーネントを異なるコード ブロックに分割し、ルートにアクセスするときに対応するコンポーネントをロードすると、より効率的になります。

//方式1, 在导入时处理
const UserDetails = () => import('./views/UserDetails.vue') 
//方式2,无需导入组件, 在定义路由中
component: ()=> import('./views/UserDetails.vue')

(8) ナビゲーションガード

ジャンプやキャンセルでガードナビゲーション

// 取消路由, 取消后就无法访问
 router.beforeEach((to,from)=>{
   return false
})

// 全局路由守卫
router.beforeEach((to,from, next)=>{
    // 检测是否登录
    if(to.name !== 'login'){
        next({name: 'login'})
    }else{
        next()
    }
})

// 独享路由守卫, 写在路由配置中
const routes = [
  {
    path: '/users/:id',
    component: UserDetails,
    beforeEnter: (to, from) => {
      // reject the navigation
      return false
    },
  },
]

公式ドキュメントを参照してください。

https://router.vuejs.org/zh/introduction.html

おすすめ

転載: blog.csdn.net/qq_54379580/article/details/129130364