第三十一章 Vue之路由(VueRouter)

发布于:2024-11-04 ⋅ 阅读:(123) ⋅ 点赞:(0)

目录

一、引言

1.1. 路由介绍

二、VueRouter

三、VueRouter的使用

3.1. 使用步骤(5+2)

3.2. 完整代码

3.2.1. main.js

3.2.2. App.vue

3.2.3. Friend.vue

3.2.4. My.vue

3.2.5. Find.vue


一、引言

1.1. 路由介绍

Vue中路由就是路径和组件的映射关系,通过指定路径和组件的对应关系,实现单页面应用中的跳转显示(即页面内容的切换)。

https://music.163.com/#/my/  My.vue组件 

https://music.163.com/#/friend  Friend.vue组件

二、VueRouter

官网地址:https://v3.router.vuejs.org/zh/

我们在Vue的开发过程中,Vue官方已经为我们提供了一个第三方路由插件,因此我们只需要在工程中安装该插件,并通过代码进行引用即可快速实现路由的功能,这个插件就是VueRouter。

VueRouter的作用就是我们前面提到的在修改地址栏路径时,切换显示匹配的组件(即页面内容)

三、VueRouter的使用

3.1. 使用步骤(5+2)

5个基础步骤

① 下载 VueRouter 模块到当前工程

② 引入

③ 安装注册

④ 创建路由对象

⑤ 注入,将路由对象注入到new Vue实例中,建立关联

2个核心步骤

① 创建需要的组件 (views目录),配置路由规则

② 配置导航,配置路由出口(路径匹配的组件显示的位置)

3.2. 完整代码

3.2.1. main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Find from './views/Find'
import Friend from './views/Friend'
import My from './views/My'

Vue.config.productionTip = false

// 路由的使用步骤(5+2)
// 5个基础步骤
// 1.下载VueRouter模块到当前工程
// 2.引入
// 3.安装注册 Vue.use(Vue插件)
Vue.use(VueRouter)
// 4.创建路由对象
const router = new VueRouter({
  // routes 路由规则
  // route 一条路由规则 { path: 路径, component: 组件}
  routes: [
    { path: "/find", component: Find },
    { path: "/my", component: My },
    { path: "/friend", component: Friend }
  ]
})
// 5.注入到new Vue中,建立关联
new Vue({
  render: h => h(App),
  router
}).$mount('#app')

// 2个核心步骤
// 1.建组件,配规则
// 2.准备导航链接,配置路由出口(匹配的组件展示的位置)

3.2.2. App.vue

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

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

<style>
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>

3.2.3. Friend.vue

<template>
  <div>
    <p>我的朋友</p>
    <p>我的朋友</p>
    <p>我的朋友</p>
    <p>我的朋友</p>
  </div>
</template>

<script>
export default {
  name: 'MyFriend'
}
</script>

<style>

</style>

3.2.4. My.vue

<template>
  <div>
    <p>我的音乐</p>
    <p>我的音乐</p>
    <p>我的音乐</p>
    <p>我的音乐</p>
  </div>
</template>

<script>
export default {
  // 给组件定义一个多单词名字,避免ESLint校验时抛出组件单个单词命名的校验异常
  name: 'MyMusic'
}
</script>

<style>

</style>

3.2.5. Find.vue

<template>
  <div>
    <p>发现音乐</p>
    <p>发现音乐</p>
    <p>发现音乐</p>
    <p>发现音乐</p>
  </div>
</template>

<script>
export default {
  name: 'FindMusic'
}
</script>

<style>

</style>


网站公告

今日签到

点亮在社区的每一天
去签到