0
点赞
收藏
分享

微信扫一扫

Vue学习笔记:路由开发 Part 02

在觉 2023-08-06 阅读 55

在上一篇中,默认情况下浏览器控制台会提示

 [Vue Router warn]: No match found for location with path "/"

Vue学习笔记:路由开发 Part 02_Vue

这是因为没有定义path为/的情况导致的。在实际使用中,可以将/通过路由进行绑定,也可以通过重定向,进行跳转。

路由重定向

为/,通过redirect进行重定向

import {createRouter, createWebHashHistory} from 'vue-router'
import Center from '../views/CenterView.vue'
import Film from '../views/FilmView.vue'
import Cinema from '../views/CinemaView.vue'
const routes = [
    {
        path:"/film",
        component:Film
    },
    {
        path:"/center",
        component:Center
    },
    {
        path:"/cinema",
        component:Cinema
    },
    {
        path:'/',
        redirect:'/film'
    }
]
const router = createRouter({
    history:createWebHashHistory(),
    routes
})
export default router

在routes中添加了,用于将/,重定向到/film

    {
        path:'/',
        redirect:'/film'
    }

此时打开/会直接重定向到/film


命名路由

可以在路由定义中添加name,为路由命名。同样,在重定向中用name代替path

    {
        path:"/film",
        name:"film",
        component:Film
    },
    {
        path:"/center",
        name:"center",
        component:Center
    },
    {
        path:"/cinema",
        name:"cinema",
        component:Cinema
    },
    {
        path:'/',
        // redirect:'/film'
        redirect:{
            name:"film"
        }
    }
]

路由别名

除了命名路由,还可以给路由别名alias

const routes = [
    {
        path:"/film",
        name:"film",
        component:Film
    },
    {
        path:"/center",
        name:"center",
        alias:"/wode",
        component:Center
    },
    {
        path:"/cinema",
        name:"cinema",
        component:Cinema
    },
    {
        path:'/',
        // redirect:'/film'
        redirect:"Cinema"
    }
]

 

Vue学习笔记:路由开发 Part 02_Vue_02


路由匹配

 将给定匹配模式的路由映射到同一个组件,路径参数 用冒号 :

当一个路由被匹配时,它的 params 的值将在每个组件中以 this.$route.params 的形式暴露出来。

在这里,添加一个新的视图组件

DetailView.vue

<template>
    <div> {{ $route.params.name }}</div>
</template>

在router.js中添加路由匹配

    {
        path:"/detail/:name",
        name:"detail",
        component:Detail
    },

Vue学习笔记:路由开发 Part 02_Vue_03


举报

相关推荐

0 条评论