-
什么是前端路由?
在web开发中,路由是指根据url分配到对应的处理程序
-
vue-router作用:管理url,实现url和组件的对应,和通过url进行组件之间的切换
-
单页应用(SPA):加载单个HTML,在用户与应用程序交互时动态更新该页面
-
步骤
- 安装模块:npm install vue-router --save
- 引入模块:import VueRouter from 'vue-router'
- 作为Vue的插件:Vue.use(VueRouter)
- 创建路由实例对象:new VueRouter({... ...})
- 注入Vue选项参数:new Vue({... ... router})
- 指定路由渲染的位置:<router-view></router-view>
src/router/index.js
- 配置hash和history模式:mode: 'history'
- 激活时的class名称:linkActiveClass: 'is-avtive'
- 给url起别名:alias: '/index', 但激活状态不会生效
- 重定向:
- redirect: '/home'
- redirect: {path:'/home'}
- redirect: {name:'HOME'}
- 动态设置重定向目标 redirect:(to)=>{ console.log('目标路由对象') console.log(to) return '/home' }
import Vue from 'vue' import Router from 'vue-router' import home from '../components/home' import document from '../components/document' import about from '../components/about' import notFound from '../components/404' Vue.use(Router) export default new Router({ mode: 'history', linkActiveClass: 'is-avtive', routes: [ { path: '/', redirect: {name:'HOME'} }, { path: '/home', //url路径 alias: '/index', //别名 name: 'HOME', //起名 component: home //映射组件 }, { path: '/document', component: document }, { path: '/about', component: about }, { path: '*', // component: notFound // 重定向 // redirect: '/home' // redirect: {path:'/home'} // redirect: {name:'HOME'} // 动态设置重定向目标 redirect:(to)=>{ console.log('目标路由对象') console.log(to) return '/home' } } ] })
src/main.js
import Vue from 'vue' import App from './App' import router from './router' import './assets/css/App.css' Vue.config.productionTip=false /* eslint-disable no-new */ new Vue({ el: '#app', router: router, components: {App}, template: '<App/>' })
src/components/home.vue
<template> <div>主页</div> </template> <script> export default { name: 'home' } </script> <style scoped> </style>
src/App.vue
router-link配置:
- to:链接,会自动生成hash和history模式下的url
- :to:动态绑定数据,也可以为对象,如:{path:'/document'}
- tag:生成的标签名
- active-class:激活状态的class名
- event="mouseover":改变切换url触发方式为鼠标移入
- exact:修改包含匹配为精确匹配
router-view配置:
- class等属性会给渲染出来的所有对象加上
<template> <div id="app"> <ul class="nav"> <router-link :to="homeUri" tag="li">home</router-link> <router-link :to="documentUri" tag="li">document</router-link> <router-link :to="aboutUri" tag="li">about</router-link> </ul> <router-view class="content"/> </div> </template> <script> export default { name: 'App', data () { return { homeUri: '/home', documentUri: '/document', aboutUri: '/about' } } } </script> <style> </style>
src/assets/css/home.css
body,ul, li{ list-style: none; margin: 0; } .nav{ background-color: cadetblue; text-align: center; width: 100%; height: 100px; font-size: 30px; } .nav li{ display: inline-block; line-height: 100px; padding: 0 20px; color: white; cursor: pointer; } .nav .is-avtive{ background-color: darkseagreen; } .content{ text-align: center; margin: 50px; }