vue-router4 |name的作用|query傳參|parmas傳參|動態路由參數|命名視圖|別名alias|前置路由守衛|路由過渡效果|滾動行為

vue-router4 出現 No match found for location with path “/”

#### router/index.ts文件
import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'home', //這裡的name
        component:()=>import('../pages/test/test.vue')
    },
    {
        path: '/home',
        name: 'home', //這裡的name
        component:()=>import('../pages/home/home.vue')
    },
]
const router = createRouter({
   history:createWebHashHistory(), //哈希值模式
    routes
})
// 暴露出去
export default router

出現問題的原因

在控制台出現,找不對應的路徑 No match found for location with path "/"
在瀏覽器上出現空白頁面。
是因為你的路由 name欄位重複導致的。

vue-router中的name有什麼作用呢?

1.路由中的name應該是唯一值,不應該重複。
router-link 中的to屬性通過name的值可以進行路由跳轉

<template>
  <router-link :to="{name:'home'}">去測試頁面</router-link>
  <router-view></router-view>
</template>

const routes: Array<RouteRecordRaw> = [
    {
        path: '/home',
        name: 'home', //這個name應該是唯一值
        component:()=>import('../pages/home/home.vue')
    },
]
a標籤通過 <a href="/home">進行跳轉的時候。
整個頁面會重新刷新(左上角的圈圈會刷新),頁面會閃一下
router-link 進行跳轉的時候整個頁面不會重新刷新 [頁面不會閃一下]

跳轉的時候不保留當前頁面的歷史記錄 router.replace

就是說A頁面跳轉到B頁面的時候。
不保留A頁面的歷史記錄。我們可以通過router.replace('/b')

query 傳遞參數和接受參數

let paramsinfo = {
  name: 'zs',
  age:13
}
const gotosPage = () => { 
  router.push({
    path: '/home',
    query: paramsinfo
  })
}
query傳遞參數的時候是只能夠是一個對象。
query傳遞參數的時候在地址欄會自動給你使用"?和&鏈接"

接受參數的時候通過 route.query.xxx

parmas 傳遞參數和接受參數

parmas傳遞參數的時候,不會在地址欄展示。
它是通過記憶體來傳遞參數的。
router.push({
    name:'你路由中的name',
    parmas:'是一個對象'
})

接受參數的時候
route.params.xxx
需要注意的是:由於它是通過記憶體來傳遞參數的,在接受頁面刷新的時候,參數肯定會丟失的。
可以通過動態路由傳遞參數來解決

動態路由參數

#### index.ts文件
{
  path: '/',
  name: 'test',
  component:()=>import('../pages/test/test.vue')
},
{
  path: '/home/:idkey', //注意這裡的idkey
  name: 'Home',
  component:()=>import('../pages/home/home.vue')
}

#### 跳轉到home頁面
const gotosPage = (mess) => { 
  router.push({
    name: 'Home',
    params: {
      //必須和路由路徑中的idkey保持一致
      idkey: mess.id
    }
  })
}

#### 接受參數
import { useRoute } from 'vue-router'
let route = useRoute()
console.log(route.params.idkey)

動態路由參數的場景

當我們從列表頁進入詳情頁的時候,
就可以使用動態路由參數來解決這個問題

命名視圖

index.ts文件
{
  path: '/aa',
  name: 'Aa',
  component: () => import('../pages/aa/aa.vue'),
  children: [
    {
      path: '/user1',
      components: {
        default:()=> import("../components/user1.vue")
      }
    },
    {
      path: '/user2',
      components: {
        Bb2: () => import("../components/user2.vue"),
        Bb3:()=> import("../components/user3.vue")
      }
    }
  ]
}


aa.vue文件
<template>
  <div>
    <h2>父頁面</h2>
    <router-link to="/user1" style="margin-right:10px">user1</router-link>
    <router-link to="/user2">user2</router-link>
    <router-view></router-view>
    <router-view name="Bb2"></router-view>
    <router-view name="Bb3"></router-view>
  </div>
</template>

當地址欄是user1的時候,默認展示的是user1這個頁面。
當地址欄是user2的時候,默認展示的是user2和user2這兩個頁面

路由重定向 redirect

redirect的值可以是一個字元串,也可以是一個回調函數。
index.ts文件
{
  path: '/aa',
  name: 'Aa',
  //重定向到user1。並且攜帶了參數
  redirect: () => { 
    return {
      path: '/user1',
      query: {
          name:'zs'
      }
    }
  },
  component: () => import('../pages/aa/aa.vue'),
  children: [
      {
        path: '/user1',
        components: {
          default:()=> import("../components/user1.vue")
        }
      },
      {
        path: '/user2',
        components: {
          Bb2: () => import("../components/user2.vue"),
          Bb3:()=> import("../components/user3.vue")
        }
      }
  ]
},

別名alias

{
    path: '/',
    alias:['/a1','/a2'],
    name: 'test',
    component:()=>import('../pages/test/test.vue')
}
路徑不同,但是訪問的都是同一個組件。

前置路由守衛 (router.beforeEach) 設置title

main.ts文件
router.beforeEach((to,from,next) => { 
    document.title = to.meta.title
    next()
})
//有ts報錯資訊
不能將類型「unknown」分配給類型「string」。


在index.ts文件
//中定義路由title的類型
declare module 'vue-router' {
    interface RouteMeta{
        title:string
    }
}

路由過渡效果

animate.css的地址: //animate.style/ 
第一步:下載  cnpm install animate.css --save
因為等會我們的動畫效果將會使用這個庫


第二步:在index.ts文件中設置動畫樣式
//這裡我們使用的是 animate__fadeIn 漸入的效果
import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router'
// 定義類型
declare module 'vue-router' {
    interface RouteMeta{
        title: string,
        transition ?:string
    }
}
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'test',
        meta: {
            title: '首頁',
            //動畫效果漸入
            transition:"animate__fadeIn",
        },
        component:()=>import('../pages/test/test.vue')
    },
]
const router = createRouter({
   history:createWebHashHistory(), //哈希值模式
    routes
})
// 暴露出去
export default router


第三步使用動畫效果 app.vue文件中
<template>
  <router-view #default="{ route, Component }">
    <!-- 使用方法,在class里加上類animate__animated與任何動畫名稱一起添加到元素,此處為漸入的效果 -->
    <transition :enter-active-class="`animate__animated ${route.meta.transition}`">
      <component :is="Component"></component>
    </transition>
  </router-view>
</template>
<script lang="ts" setup>
//引入動畫庫
import 'animate.css';
</script>

滾動行為

A頁面有滾動條,在距離頂部400px的地方。點擊按鈕前往了B頁面。
當B頁面做完一些操作後,返回A頁面。滾動條仍然在400px的地方。
index.ts文件
const router = createRouter({
    history: createWebHashHistory(), //哈希值模式
    // 路由滾動
    scrollBehavior: (to, from, savePosition) => {
        // 記錄滾動條滾動到的位置
        if (savePosition && savePosition.top) { 
          return savePosition
        } else {
          return {
            top:0
          }
        }
    },
    routes
})

scrollBehavior也是支援非同步的
const router = createRouter({
    history: createWebHashHistory(), //哈希值模式
    // 路由滾動
    scrollBehavior: (to, from, savePosition) => {
        // 記錄滾動條滾動到的位置
        return new Promise((resolve) => { 
            setTimeout(() => {
                resolve({
                    top:500
                })
            },1500)
        })
    },
    routes
})