Vue Router 基础

239 阅读2分钟

vue-router引入

// 注意: 不能使用 import VueRouter from "vue-router" 引入

// 引入方法
import {createRouter, createWebHistory} from 'vue-router'
// 设置路由配置
const routes = [ 
    {
        path:"/home",
        component:() =>import("@/components/home")
    },
    {
        path:"/about",
        component:() =>import("@/components/about")
    }
]
// 创建路由对象
const router = createRouter({
    history: createWebHistory(),
    routes
})
//导出默认路由对象
export default router;

router对象配置

history配置

// 注意: 使用无论哪一种模式,都得提前引入
 import {createRouter, createWebHistory,createWebHashHistory} from 'vue-router'
-----------------------------------
// history 模式
createWebHistory()
http://localhost:8080/home/news
---------------------------------
// hash 模式
createWebHashHistory()
http://localhost:8080/home/news#/about

routes配置

const routes = [
    {
        path: 路径参数             "/"
        name: 路由的名字           "home"
        component: 对应的组件      ()=>import("@/views/home.vue")
        redirect:路由重定向        "/home" 或 {name:"home"} 
        alias: 别名                "/home" 
        props: 传递参数             true
        meta:  元数据               {keepAlive:true}
    }
]

路由懒加载

// 路由懒加载   推荐使用
优点: 不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件
router.js
---------------------------------------------------
const routes = [
    {
        path:"/home",
        component:() =>import("@/components/home") // <-组件
    },
    {
        path:"/about",
        component:() =>import("@/components/about") // <-组件
    }
]
// 普通引入  不推荐使用
// 缺点: 当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。
import Home from "@/components/home"
import About from "@/components/about"
// 设置路由配置
router.js
-------------------------------------------------
const routes = [ 
    {
        path:"/home",
        component:Home // <-组件
    },
    {
        path:"/about",
        component:About // <-组件
    }
]

路由导航

params

// 使用: /users/:username/posts/:postId
// 匹配到的路径参数会被放进 this.$route.params 对象中
// 如 /users/eduardo/posts/123 -> { username: 'eduardo', postId: '123' }

const routes = [
    {
        path:"/users/:userid",
        component:() =>import("@/components/users")
    },
]

注意: params 对象写法不能使用 path ,得使用 name
因为动态路由也是传递params的,即{path:'/user/123',params:{user:'456'}}会产生冲突

// 声明式常规写法
<router-link to="/user/777">user</router-link>
// 声明式对象写法
<router-link :to="{name:"user",params:{userid:999}">user</router-link>
// 编程式常规写法
this.$router.push("/user/888")
// 编程式对象写法
this.$router.push({name:"user",params:{userid:999}})

query

// 使用: /search?query
// 匹配到的query会被放进 this.$route.query 对象中 
// 如:/search?username=nana&userid=2233 -> {username:"nana",userid:"2233"}

注意: query 既可以使用 path 也可以使用 name
// 声明式常规写法
<router-link to="/search?username=nana&userid=2233">search</router-link>
// 声明式对象写法
<router-link :to="{path:'/search',query:{username:'nana'}}">search</router-link>
// 编程式常规写法
this.$router.push("/search?username=nana&userid=2233")
// 编程式对象写法
this.$router.push({path:'/search',query:{username:'nana',userid:5588}})

params或query为空

this.$router.push({
    name: "about",
    // params传空字符串相当于没传
    params: { id: ""  || undefined },
    // query传空字符串相当于 ?id=
    query: { id: "" || undefined },
})

params参数可传可不传

{
    path: "/about/:id?",
    component: () => import("@/views/about"),
    props: (route) => route.params,
    name: 'about',
},

捕获404

// 捕获没有的url
// 如访问 /nana就会匹配到404路由,因为我们没有配置这个路由
-----------------------------------------------------
const routes = [
    {
        path:"/home",
        component:() =>import("@/components/home")
    },
    {
        path:"/about",
        component:() =>import("@/components/about")
    },
    // 将404路由放到最后,因为路由是从上到下匹配,如果没有匹配到就会匹配到404路由
    {
        path:"/:pathMatch",
        component:() =>import("@/components/notfound")
    }
]

路由传参

相当于在路由组件中使用 :="props"

布尔值传递

// 相当于直接传递`route.params`对象
{
    path: "/about/:id/name/:paid",
    component: () => import("@/views/about"),
    props: true
}

对象传递

// 传递对象
{
    path: "/profile",
    component: () => import("@/views/profile.vue"),
    props: { userage: 20 }
}

函数传递

// 传递params对象
{
    path: "/about/:id",
    component: () => import("@/views/about"),
    props: (route) => route.params,
    name: 'about'
},
// 传递query对象
{
    path: "/profile",
    component: () => import("@/views/profile.vue"),
    props: (route) => route.query,
    name: 'profile'
}
// 只传递其中之一
  {
    path: "/about/:id/name/:paid",
    component: () => import("@/views/about"),
    props: (route) => {
        return {
            paid:route.params.paid
        }
    },
    name: 'about'
  }

嵌套路由

// 路由中嵌套路由
// 嵌套路由中不必写 "/news" 直接写 "news"
router.js
------------------------------------------------------
const routes = [
    {
        path:"/home",
        component:() =>import("@/components/home"),
        children:[
            {
                path:"news",
                component:() =>import("@/components/homenews")
            },
            {
                path:"acg",
                component:() =>import("@/components/homeacg")
            }
        ]
    }
]
App.vue
-----------------------------------------------------
<div>
  <router-link to="/home">home</router-link>  
  <router-link to="/about">about</router-link>
  <router-view></router-view>
</div>
home.vue
------------------------------------------------------
<template>
  <div>
      <h2>我是主页</h2>
      <router-link to="/home/news">news</router-link>
      <router-link to="/home/acg">acg</router-link>
      <router-view ></router-view>
  </div>
</template>

命名视图

router.js
-------------------------------------------------------
//  必须这样导入,因为我们是要同时展示
import home from "../components/home.vue"
import homenews from "../components/homenews.vue"
import homeacg from "../components/homeacg.vue"

//  components里的名字必须和 router-view 的一样
const routes = [
    {
        path:"/home",
        components:{
            default:home,
            acg:homeacg,
            new:homenews
        }
    }
]
App.vue
---------------------------------------------------
<router-view></router-view>
<router-view  name="acg"></router-view>
<router-view  name="news"></router-view>