VueRouter的使用

路由的封装抽离:在src目录下新建router文件夹,router文件下新建index.js文件,在里面配置路由。好处:拆分模块,利于维护。

一、5个基本步骤

1.下载:下载VueRouter模块到当前工程。命令:npm i vue-router@3

2.引入:

import Vue from 'vue'

import VueRouter from 'vue-router'

3.安装注册:Vue.use(VueRouter)

4.创建路由对象:const router = new VueRouter( )

5.注入:将路由对象注入到new Vue实例中,建立关联。

new Vue({

render: h => h(App),

router

}).$mount('#app')

二、2个核心步骤

1.创建需要的组件(views目录),配置路由规则(路径和组件的匹配关系)。

2.配置导航,配置路由出口 router-view (路径对应的组件显示的位置)

router 下的index.js如下

复制代码
//  @/views 绝对路径 : 基于 @ 指代 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'

//VueRouter插件初始化
Vue.use(VueRouter)

//创建路由对象
const router = new VueRouter({
  //路由规则们,数组包对象。一条路由规则{path:路径,component:组件}
  routes: [
    { path: '/find', component: Find },
    { path: '/my', component: My },
    { path: '/friend', component: Friend }
  ],
  //自定义类名
  linkActiveClass: 'active',   //配置模糊匹配的类名
  linkExactActiveClass: 'exact-active'   //配置精确匹配的类名
})

export default router

App.vue如下(简单介绍 router-link )

复制代码
<template>
  <div>
    <div class="footer_wrap">
      <!-- 
      1.router-link是什么?
        vue-router提供的全局组件,用于替换a标签
      2.router-link怎么用?
       <router-link to="/路径值"></router-link>
        必须传入to属性,指定路由路径值
      3.router-link好处?
        能跳转,能高亮(自带激活时的类名)            
       -->
      <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>
/* router-link 会自动给当前导航添加两个类名 区别 */
/*  1. router-link-active 模糊匹配(用的多) 
 to='/find => 地址栏/find  /find/one  /find/two */

/*  2. router-link-exact-active  精确匹配 
  to='/find => 地址栏/find */
.footer_wrap a.active {
  background-color: red;
}

body {
  margin: 0;
  padding: 0;
}
.footer_wrap {
  position: relative;
  left: 0;
  top: 0;
  display: flex;
  width: 100%;
  text-align: center;
  background-color: #333;
  color: #ccc;
}
.footer_wrap a {
  flex: 1;
  text-decoration: none;
  padding: 20px 0;
  line-height: 20px;
  background-color: #333;
  color: #ccc;
  border: 1px solid black;
}
.footer_wrap a:hover {
  background-color: #555;
}

</style>
相关推荐
CoderLiu1 分钟前
程序化工具调用(PTC)与动态工作流引擎:深入大模型工具调用的架构演进与实践
前端·人工智能·后端
码农胖大海12 分钟前
我的第一个产品,只有一段提示词
前端·ai编程·产品
邋遢道40 分钟前
# 企业级 Agent 从 0 到 1(二):技术选型与最小骨架
前端·chrome
计算机魔术师43 分钟前
我看了 OpenAI 首席科学家的最新长文,把原来的认知推翻了一遍
前端
乱码三千1 小时前
使用ComfyUI+MinMax-H3音视频模型生成视频
前端·后端·github
Coder_Ke1 小时前
代码我都定位了,Codex 还在考古:于是我写了个 VS Code 插件
前端
LiaCode2 小时前
别让 AI 把仓库写成“代码平行宇宙”:从 Deslop 看生成前查重
前端·后端·github
nice先生的狂想曲3 小时前
javascript高级程序设计(六)——2026.9.5
前端·javascript
我爱写代码i3 小时前
SKAPP SK影视反编译详细教程+源码 含苹果端ipa
开发语言·javascript·ecmascript
光影少年3 小时前
如何做大型React+RN 项目架构设计、目录规范
前端·react native·react.js