如何在 Vue.js 中使用路由?

321 阅读2分钟

介绍

用 Vue + Vue Router 创建单页应用非常简单:通过 Vue.js,我们已经用组件组成了我们的应用。

Vue 路由器有助于在浏览器的 URL/历史记录和 Vue 的组件之间建立链接,允许某些路径呈现与其关联的任何视图。vue 路由器用于构建单页应用程序 (single-page applications——SPA)。

vue-router 可以在创建新项目时默认设置。在本文中,我们将单独安装它。所以我们可以看看它是如何工作的。

vue-router使用

App.vue - 页面标签和样式准备

<template>
  <div>
    <div class="footer_wrap">
      <a href="#/find">发现音乐</a>
      <a href="#/my">我的音乐</a>
      <a href="#/part">朋友</a>
    </div>
    <div class="top">
      
    </div>
  </div>
</template>

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

<style scoped>
.footer_wrap {
  position: fixed;
  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;
}
.top {
  padding-top: 62px;
}
</style>

以下指令可在main.js中配置

1. 安装(可以通过 Npm 安装 Vue Router,vue2不支持4以上的版本,这里安装3.5.3)

npm i vue-router@3.5.3

2. 导入路由main.js中

import VueRouter from 'vue-router'

3.使用路由插件

Vue.use(VueRouter)

4. 创建路由对象

const router = new VueRouter({ })

5. 关联到vue实例(在new Vue中加入)

new Vue({ router })

6. 配置路由规则
// 4. 创建一个路由对象
const router = new VueRouter({
  // 路由的规则
  // route: 一条路由规则
  routes: [
    {
      // 路径 锚点
      // 组件
      path: '/find',
      component: Find,
    },
    {
      path: '/my',
      component: My,
    },
    {
      path: '/friend',
      component: Friend,
    },
  ],
})
7. 指定路由的出口(在App.vue中加入)
<div class="top">
  <!-- 路由的出口 -->
  <router-view></router-view>
</div>

路由的封装

  • 新建文件router/index.js
import Vue from 'vue'
// 2. 导入VueRouter
import VueRouter from 'vue-router'

import Find from '../views/Find'
import My from '../views/My'
import Friend from '../views/Friend'

// 3. 使用vue插件  vue的插件想要生效必须调用一个方法  Vue.use(XXXX)
Vue.use(VueRouter)

// 4. 创建一个路由对象
const router = new VueRouter({
  // 路由的规则
  // route: 一条路由规则
  routes: [
    {
      // 路径 锚点
      // 组件
      path: '/find',
      component: Find,
    },
    {
      path: '/my',
      component: My,
    },
    {
      path: '/friend',
      component: Friend,
    },
  ],
})

export default router

image.png

  • main.js中
import router from './router'

new Vue({
  // 5. 关联路由对象和vue实例 data methods
  render: (h) => h(App),
  router,
}).$mount('#app')

image.png

  • 项目文件夹

image.png

  • 最终效果 2022-12-11 21-44-28.gif