路由进阶

本文详细介绍了Vue.js中的路由管理,包括路由封装抽离、声明式导航的高亮和参数传递、编程式导航的两种方式、重定向、404处理以及路由模式设置。
摘要由CSDN通过智能技术生成


在这里插入图片描述

1.路由的封装抽离

问题:所有的路由配置都堆在main.js中合适吗?
目标:将路由模块抽离出来。好处:拆分模块,利于维护
之前所添加的路由配置都是写在main.js中的
在这里插入图片描述
方法:src下面新建一个文件router,里面建一个index.js,在里面导入router

index.js
//一直换路径很麻烦,可以用@/view.Find(@就是src,就直接从src下面找,是绝对路径)
import Find from '../views/Find'
import My from '../views/My'
import Friend from '../views/Friend'

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) //VueRouter插件初始化

//创建了一个路由对象
const router = new VueRouter({
  //routes 路由规则们
  routes:[
    {path:'/find',component:Find},
    {path:'/my',component:My},
    {path:'/friend',component:Friend}
  ]
  
})
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
export default router

main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router:router
}).$mount('#app')

2.声明式导航 - 导航链接

需求:实现导航高亮效果
vue-router 提供了一个全局组件router-link(取代a标签)
功能
①能跳转,配置to属性指定路径(必须)。标签还是a标签,to无需#
②能高亮,默认就会提供高亮类名,可以直接设置高亮样式(就是在控制台中,直接找到对应的类名,两个类名,选一个就可以了)
在这里插入图片描述

在这里插入图片描述

App.vue
<template>
  <div>
    <div class="footer_wrap">
      <router-link to="/find">发现音乐</router-link>
      <router-link to="/my">我的音乐</router-link>
      <router-link to="/friend">朋友</router-link>
    </div>
    <div class="top">
      <!-- 路由出口 → 匹配的组件所展示的位置 -->
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {};
</script>

<style>

.footer_wrap a.router-link-active{
  background-color: pink;
}

</style>

在这里插入图片描述

3.声明式导航-两个类名

说明:router-link自动给当前导航添加了两个高亮类名
在这里插入图片描述
router-link=active 模糊匹配(用的多)
to="/my" 可以匹配 /my /my/a /my/b
在这里插入图片描述

router-link-exact-active 精确匹配
to="/my" 仅可以匹配 /my

自定义匹配的类名

Q:router-link的两个高亮类名太长了,希望能定制怎么办
只需要在router配置项中配两个配置项就可以了
在这里插入图片描述
在这里插入图片描述

4.声明式导航 - 跳转传参

目标:在跳转路由时,进行传值

  1. 查询参数传参
  2. 动态路由传参
查询参数传参

①语法格式如下:
to = "/path?参数名 = 值"
②对应页面组件接收传递过来的值
$route.query.参数名
👇👇

index.js
import Home from '@/views/Home'
import Search from '@/views/Search'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化

// 创建了一个路由对象
const router = new VueRouter({
  routes: [
    { path: '/home', component: Home },
    { path: '/search', component: Search }
  ]
})

export default router
Search.vue
<template>
  <div class="search">
    <!-- 从地址栏导入关键字 -->
    <p>搜索关键字: {{ $route.query.key }} </p>
    <p>搜索结果: </p>
    <ul>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MyFriend',
  created () {
    // 在created中,获取路由参数
    // this.$route.query.参数名 获取
    console.log(this.$route.query.key);
  }
}
</script>
Home.vue
<template>
  <div class="home">
    <div class="logo-box"></div>
    <div class="search-box">
      <input type="text">
      <button>搜索一下</button>
    </div>
    <div class="hot-link">
      热门搜索:
      <router-link to="/search?key=黑马程序员">黑马程序员</router-link>
      <router-link to="/search?key=前端培训">前端培训</router-link>
      <router-link to="/search?key=如何成为前端大牛">如何成为前端大牛</router-link>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FindMusic'
}
</script>
App.vue
<template>
  <div id="app">
    <div class="link">
      <router-link to="/home">首页</router-link>
      <router-link to="/search">搜索页</router-link>
    </div>

    <router-view></router-view>
  </div>
</template>

<script>
export default {};
</script>
动态路传参

①配置动态路由
在这里插入图片描述
②配置导航链接
to = "/path/参数值"
③对应页面组件接收传递过来的值
$route.params.参数名

index.js
const router = new VueRouter({
  routes: [
    { path: '/home', component: Home },
    //路由规则
    { path: '/search/:words', component: Search }//   /~/:参数名(参数名可以随便取)
  ]
})
Home.vue
 <div class="hot-link">
      热门搜索:
      <!-- 比查询参数传参的方法简洁 -->
      <router-link to="/search/黑马程序员">黑马程序员</router-link>
      <router-link to="/search/前端培训">前端培训</router-link>
      <router-link to="/search/如何成为前端大牛">如何成为前端大牛</router-link>
    </div>\
Search.vue
<template>
  <div class="search">
    <p>搜索关键字: {{ $route.params.words }} </p>
    <p>搜索结果: </p>
    <ul>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MyFriend',
  created () {
    // 在created中,获取路由参数
    // this.$route.query.参数名 获取查询参数
    // this.$route.params.参数名 获取动态路由参数
    console.log(this.$route.params.words);
  }
}
</script>
两种传参方式的区别
  1. 查询参数传参(比较适合传多个参数)
    ①跳转:to="/path?参数名=值&参数名2=值"
    ②获取:$routr.query.参数名
  2. 动态路由传参(优雅简洁,传单个参数比较方便)
    ①配置动态路由:path:"/path/参数名"
    ②跳转:to="path/参数值"
    ③获取:$route.params.参数名
动态路由参数可选符

问题:配了路由 path:“/search/:words” 为什么按下面步骤操作,回未匹配到组件,显示空白
原因:/search/:words 表示,必须要传参数。如果不传参数,也希望匹配,可以加个可选符?
在这里插入图片描述

5.Vue路由 - 重定向

问题:网页打开,url默认是 / 路径,未匹配到组件时,会出现空白
说明:重定向 → 匹配path后,强制跳转path路径
语法:{path:匹配路径,redirect:重定向到的路径}(redirect就是强制跳转到的路径)
在这里插入图片描述

index.js
// 创建了一个路由对象
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/search/:words?', component: Search }
  ]
})

6.Vue路由 - 404

作用:当路径找不到匹配时,给个提示页面(比如连接后面加了别的东西,就是不存在的链接)
位置:配在路由最后
语法path:"*"(任意路径) - 前面不匹配就命中最后这个(*的意思是匹配所有的规则)
在这里插入图片描述
在这里插入图片描述

index.js
import NotFound from '@/views/NotFound'
// 创建了一个路由对象
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/search/:words?', component: Search }
    { path: '*', component:NotFound}
  ]
})

然后在views中新建一个NotFound.vue

<template>
  <div>
    <h1>404 Not Found</h1>
  </div>
</template>

7.Vue路由 - 模式设置

问题:路由的路径看起来不自然 ,有#,能否切成真正路径形式

  • hash路由(默认) 例如:http://localhost:8080/#/home
  • history路由(常用) 例如:http://localhost:8080/home(以后上线需要服务器端支持)
    从默认模式切换到常用模式,只要加mode:"history"就可以了
    在这里插入图片描述
    不带井号了
    在这里插入图片描述
const router = new VueRouter({
  // 注意:一旦采用了 history 模式,地址栏就没有 #,需要后台配置访问规则
  mode: 'history',
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { name: 'search', path: '/search/:words?', component: Search },
    { path: '*', component: NotFound }
  ]
})

8.编程式导航 - 两种路由跳转

①path路径跳转(简易方便)
在这里插入图片描述

home.vue
<script>
export default {
  name: 'FindMusic',
  methods: {
    goSearch () {
       //1. 通过路径的方式跳转
       (1) this.$router.push('路由路径') //[简写]
       this.$router.push('/search')

       (2) this.$router.push({     //[完整写法]
               path: '路由路径' 
           })
       this.$router.push({
         path: '/search'
       })
      })
    }
  }
}
</script>

name命名路由跳转(适合 path 路径长的场景)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
要先像上面圈出来的这里起名字,然后下面的路由名与上面index.js中的对应,才能起作用

Home.vue
<script>
export default {
  name: 'FindMusic',
  methods: {
    goSearch () {


      // 2. 通过命名路由的方式跳转 (需要给路由起名字) 适合长路径
      //    this.$router.push({
      //        name: '路由名'
      //    })
      this.$router.push({
        name: 'search'
      })
    }
  }
}
</script>

9.编程式导航 - 路由传参

在这里插入图片描述
问题:点击搜索按钮,跳转需要传参如何实现?
两种传参方式:查询参数 + 动态路由传参
两种跳转方式,对于两种传参方式都支持:

  1. path路径跳转传参
    (query传参)
    在这里插入图片描述
    (动态路由传参)
    在这里插入图片描述
index.js
import Home from '@/views/Home'
import Search from '@/views/Search'
import NotFound from '@/views/NotFound'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化

// 创建了一个路由对象
const router = new VueRouter({
  // 注意:一旦采用了 history 模式,地址栏就没有 #,需要后台配置访问规则
  mode: 'history',
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { name: 'search', path: '/search/:words?', component: Search },
    { path: '*', component: NotFound }
  ]
})

export default router
Home.vue
<template>
  <div class="home">
    <div class="logo-box"></div>
    <div class="search-box">
      <input v-model="inpValue" type="text">
      <button @click="goSearch">搜索一下</button>
    </div>
    <div class="hot-link">
      热门搜索:
      <router-link to="/search/黑马程序员">黑马程序员</router-link>
      <router-link to="/search/前端培训">前端培训</router-link>
      <router-link to="/search/如何成为前端大牛">如何成为前端大牛</router-link>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FindMusic',
  data () {
    return {
      inpValue: ''
    }
  },
  methods: {
    goSearch () {
      // 1. 通过路径的方式跳转
      // (1) this.$router.push('路由路径') [简写]
      //     this.$router.push('路由路径?参数名=参数值')
      // this.$router.push('/search')
      // this.$router.push(`/search?key=${this.inpValue}`)   //跟data做双向绑定
      // this.$router.push(`/search/${this.inpValue}`)

      // (2) this.$router.push({     [完整写法] 更适合传参
      //         path: '路由路径'
      //         query: {
      //            参数名: 参数值,
      //            参数名: 参数值
      //         }
      //     })
      // this.$router.push({
      //   path: '/search',
      //   query: {
      //     key: this.inpValue
      //   }
      // })
      // this.$router.push({
      //   path: `/search/${this.inpValue}`
      // })
    }
  }
}
</script>

Search.vue//通过搜索页接收
<template>
  <div class="search">
    <p>搜索关键字: {{ $route.params.words }} </p>
    <p>搜索结果: </p>
    <ul>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MyFriend',
  created () {
    // 在created中,获取路由参数
    // this.$route.query.参数名 获取查询参数
    // this.$route.params.参数名 获取动态路由参数
    // console.log(this.$route.params.words);
  }
}

</script>
  1. name命名路由跳转传参(动态路由传参)
    在这里插入图片描述
Home.vue
<template>
  <div class="home">
    <div class="logo-box"></div>
    <div class="search-box">
      <input v-model="inpValue" type="text">
      <button @click="goSearch">搜索一下</button>
    </div>
    <div class="hot-link">
      热门搜索:
      <router-link to="/search/黑马程序员">黑马程序员</router-link>
      <router-link to="/search/前端培训">前端培训</router-link>
      <router-link to="/search/如何成为前端大牛">如何成为前端大牛</router-link>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FindMusic',
  data () {
    return {
      inpValue: ''
    }
  },
  methods: {
    goSearch () {
      // 2. 通过命名路由的方式跳转 (需要给路由起名字) 适合长路径
      //    this.$router.push({
      //        name: '路由名'
      //        query: { 参数名: 参数值 },//query传参
      //        params: { 参数名: 参数值 }//动态传参
      //    })
      this.$router.push({
        name: 'search',
        // query: {
        //   key: this.inpValue
        // }
        params: {
          words: this.inpValue
        }
      })
    }
  }
}
</script>

Search.vue//通过搜索页接收
<template>
  <div class="search">
    <p>搜索关键字: {{ $route.params.words }} </p>//通过params.words接收
    <p>搜索结果: </p>
    <ul>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
      <li>.............</li>
    </ul>
  </div>
</template>

通过什么传参就用什么接收
console
在这里插入图片描述
在这里插入图片描述

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值