官方介绍
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于 Vue.js 过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的 CSS class 的链接
- HTML5 历史模式或 hash 模式,在 IE9 中自动降级
- 自定义的滚动条行为
npm 安装 npm install --save -dev vue-router
基本使用
1、新建router 文件夹,存放路由相关文件
2、router > index.js 设置注册 router和路由
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入相关组件
import Home from '../views/Home.vue'
import News from '../views/News.vue'
import Sports from '../views/Sports.vue'
Vue.use(VueRouter)
let router = new VueRouter({
routes:[
{
//路由地址
path:'/home',
//对应路由显示对应组件
component:Home
}
........
]
})
export default router
3、在main.js中 注册router
import Vue from 'vue'
import App from './App.vue'
import iviewUi from 'view-design'
import 'view-design/dist/styles/iview.css'
import elementUi from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import i18n from './lang/index'
//全局引入Grid
import {Grid,GridItem} from './components/Grid/index'
Vue.use(elementUi)
Vue.use(iviewUi)
Vue.use(Grid)
Vue.use(GridItem)
import router from './router/index'
new Vue({
render: h => h(App),
i18n,
router
}).$mount('#app')
4、在App.vue中设置一个 router-view 组件,这是内置组件,作用是显示路由跳转的组件页面
<template>
<div>
<router-view></router-view>
</div>
</template>
浏览器中 输入 http://localhost:8080/sports#/home
即可显示组件页面
路由声明式导航
1、to属性
之前是收到输入url,没有任何触发条件,这里可以通过 router-link设置点击跳转的元素
router-link 组件默认渲染为带有链接的a标签
router-link 组件 to 是必须属性
<router-link to='home'>点击跳转到home</router-link>
2、tag属性
router-link 组件默认渲染为带有链接的a标签,通过tag属性进行配置默认显示 如如 tag设置为 li
<router-link to='home' tag="li">点击跳转到home</router-link>
3、active-class属性
active-class属性的作用是添加被激活的class类名
<router-link to='home' tag="li" active-class="aclass">点击跳转到home</router-link>
如果不设置active-class此时默认被激活的class类名是.router-link-active
配置全局的 默认激活class
router>index.js中
let router = new VueRouter({
linkActiveClass: 'is-active',
routes: [{
// 路由地址
path: '/home',
// 对应的路由显示的组件
component: Home
},
{
path: '/sport',
component: Sport
}
]
})
4、exact属性
exact属性是精确匹配
比如路由地址有/add和/add/a,如果触发了/add/a,此时/add的路由也会被激活class状态
设置exact来精确匹配
<router-link to='/home' exact exact-active-class="eclass" tag="li">点击跳转到home</router-link>
exact-active-class="eclass" 精确匹配时的 被激活class配置
5、event属性
通过event属性设置router-link被触发的方式
<router-link to='/home' event='mouseenter' tag="li">点击跳转到home</router-link>
此时触发的方式是 mouseenter
6、 replace属性
路由跳转有 router和replace,如果是router会记录跳转地址,replace 不会记录
<router-link to='/home' replace tag="li">点击跳转到home</router-link>
<router-link to='/home/add' replace tag="li">点击跳转到home/add</router-link>
replace 模式下不 浏览器不能返回上次的地址
7、append属性
append属性是在当前的路由基础之上,进行累加,而不是重构
<router-link to='home' append tag="li">点击跳转到home</router-link>
<router-link to='sport' append tag="li">点击跳转到sport</router-link>
此时页面会有反复累加的状态
注意,如果需要设置需要append状态的路由,前面不加 "/"