Vue路由介绍和路由配置

148 阅读2分钟

单页应用程序与路由

SPA - 单页应用程序

  • SPA: Single Page Application 单页面应用程序
  • MPA : Multiple Page Application多页面应用程序

优势

  • 传统的多页面应用程序,每次请求服务器返回的都是一整个完整的页面
  • 单页面应用程序只有第一次会加载完整的页面
  • 以后每次请求仅仅获取必要的数据,减少了请求体积,加快页面响应速度,降低了对服务器的压力
  • SPA更好的用户体验,运行更加流畅

缺点

  1. 开发成本高 (需要学习路由) vue-router react-router
  2. 不利于 SEO 搜索引擎优化 谷歌浏览器在解决这个问题 ssr:服务端渲染 server side rendering

路由介绍

  • 路由 : 是浏览器 URL 中的哈希值( # hash) 与 展示视图内容(组件) 之间的对应规则

    • 简单来说,路由就是一套映射规则(一对一的对应规则), 由开发人员制定规则.-
    • 当 URL 中的哈希值( # hash) 发生改变后,路由会根据制定好的规则, 展示对应的视图内容(组件)
  • 为什么要学习路由

    • 渐进式 =>vue => vuer-router (管理组件之间的跳转)
    • 在 web App 中, 经常会出现通过一个页面来展示和管理整个应用的功能.
    • SPA 往往是功能复杂的应用,为了有效管理所有视图内容,前端路由 应运而生.
  • vue 中的路由 : 是 hashcomponent 的对应关系, 一个哈希值对应一个组件

vue-router介绍

路由 - 组件分类

.vue文件分2类, 一个是页面组件, 一个是复用组件

src/views(或pages) 文件夹 和 src/components文件夹

  • 页面组件 - 页面展示 - 配合路由用
  • 复用组件 - 展示数据/常用于复用

image.png

vue-router使用

  • 安装
yarn add vue-router@3.5.3
  • 导入路由 main.js
import VueRouter from 'vue-router'
  • 使用路由插件
// 在vue中,使用使用vue的插件,都需要调用Vue.use()
Vue.use(VueRouter)
  • 创建路由对象
const router = new VueRouter({
})
  • 关联到vue实例
new Vue({
  router
})

==效果:地址栏中自动增加了 #==

image.png

配置路由规则

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

==必须指定路由的出口==

<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
​
  • main.js中
import router from './router'new Vue({
  // 5. 关联路由对象和vue实例 data methods
  render: (h) => h(App),
  router,
}).$mount('#app')