安装
npm intall vue-router --save
使用
router/index.js
文件中
import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由对象
Vue.use(VueRouter)
// 配置路由和组件之间的应用关系
const routes = [
// 重定向
{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
}, {
path: '/about',
component: About
}
]
const router = new VueRouter({
routes
})
// 导出 router
export default router
main.js
中
import router from './router'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
Vue,use(插件)
插件的使用方式
router-link属性
router-link 默认渲染为a标签
to
去往某个路由
tag
属性可以设置router-link
渲染的样式
replace
后退键不能返回到上一个页面中
linkActiveClass
给被选中的class改名字
<router-link to="/home" tag="button"></router-link>
动态路由
router/index.js
{
path: '/user/:userId',
component:User
}
$router
整个VueRouter 对象
$route
正活跃的当前路由
路由懒加载
const Home = ()=> import(../../views/Home/Home.vue)
路由的嵌套
- 创建对应的子组件,并且在路由映射中配置对应的子路由
- 在组件内部使用
<router-view>
标签
{
path: '/home',
name: 'Home',
component: Home,
children: [
{
path: '',
redirect: 'message'
},
{
path: 'message',
component: Message
}
]
},
子组件里
path
没有/
路由传参
在vue原型上挂载属性
// 在main.js中
vue.prototype.name = 'code'
// 在其他界面
this.$name()
导航守卫
以下称之为“全局守卫”
// 路由跳转前进行
// 前置守卫(guard)
router.beforeEach((to, from, next) => {
// 从from跳转到to
document.title = to.matched[0].meta.title
// 一定要调用
next()
})
// 路由跳转后
//后置钩子(hook)
router.afterEach((to, from) => {
// 内容
})
前置守卫一定要主动调用
next()
函数,后置钩子不用
keep-alive
使组件不要频繁的被创建、被销毁
<keep-alive exclude="User">
<router-view/>
</keep-alive>
只有在使用
keep-alive
的前提下才能使用activated()
和deactivated()
里面不要随便加空格