返回

前端路由一览,初学者秒懂核心概念

前端

初识前端路由

前端路由(Front-end Routing)是构建单页面应用(Single Page Application,SPA)的关键技术之一。在 SPA 中,整个应用只有一个 HTML 页面,所有的页面切换都在该页面内部进行,从而避免了传统多页面应用每次切换页面都要重新加载整个页面的问题,提高了应用的性能和用户体验。

前端路由的核心思想是将不同的页面内容映射到不同的 URL 路径,当用户在浏览器中访问不同的 URL 时,前端路由会动态加载相应的页面内容并展示在页面上,而无需重新加载整个页面。

Vue-router,前端路由利器

Vue-router 是 Vue.js 官方推荐的前端路由库,它提供了一系列易用且强大的功能,帮助你轻松构建复杂的单页面应用。

使用 Vue-router

  1. 安装 Vue-router
npm install vue-router
  1. 在 Vue.js 实例中注册 Vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ]
})

const app = new Vue({
  router
}).$mount('#app')
  1. 在组件中使用路由
<template>
  <div>
    <h1>{{ $route.name }}</h1>
    <router-view />
  </div>
</template>

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

路由传参

Vue-router 支持两种路由传参方式:

  1. 查询参数
this.$router.push({ path: '/user', query: { id: 123 } })
  1. 路由参数
this.$router.push({ path: '/user/:id', params: { id: 123 } })

路由守卫

Vue-router 提供了三种路由守卫,可以让你在路由切换时执行一些额外的操作:

  1. 全局前置守卫
router.beforeEach((to, from, next) => {
  // ...
})
  1. 全局后置守卫
router.afterEach((to, from) => {
  // ...
})
  1. 路由独享守卫
const Home = {
  beforeRouteEnter(to, from, next) {
    // ...
  }
}

路由模式

Vue-router 提供了两种路由模式:

  1. hash 模式
const router = new VueRouter({
  mode: 'hash'
})
  1. history 模式
const router = new VueRouter({
  mode: 'history'
})

Vue-router 与 Vue 钩子

Vue-router 和 Vue 钩子可以很好地配合使用,实现更复杂的路由控制。

Vue-router 钩子:

beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave

Vue 钩子:

created
mounted
updated
beforeDestroy

结语

以上就是前端路由的基础入门,希望对你有帮助。如果你想了解更多关于 Vue-router 的内容,可以参考官方文档。