一、安装
npm install vue vue-router
二、使用
在项目src
下新建router
文件夹,然后创建index.js
,import
所需的模块,Vue.use()
使用插件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
先创建一个路由映射routes
import Home from 'src/components/Home'
const routes = [
{ //配置默认路由
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home,
meta: {
title: '首页'
},
children: [ //创建子路由
{
path: 'child1',
component: HomeChild1,
},
{
path: 'child2',
component: HomeChild2,
}
]
},
{
path: '/about',
component: () => import 'src/components/About', //懒加载,打包会独自生成一份js文件
meta: {
title: '关于'
},
},
{
path: '/user/:id', //带占位符 id 的路由
component: () => import 'src/components/User',
meta: {
title: '用户'
},
}
]
然后将路由映射routes
挂载到VueRouter
的实例对象router
上
const router = new VueRouter({
routes, //挂载路由映射
mode: 'history', //设置路由模式,默认是hash
linkActiveClass: 'active', //将router-link的活跃状态下的类改为'active'
linkExactActiveClass: 'acive' //只有一个link显示样式,上面存在2个显示的可能
})
//前置守卫
router.beforeEach((to,from,next) => {
//to 代表路由的目标route对象,from 代表起始路由route对象
document.title = to.matched[0].meta.title //使用全局导航守卫修改 title
next() //必须调用
})
//后置钩子
router.afterEach((to,from) => {
//to 代表路由的目标route对象,from 代表起始路由route对象
console.log('完成了路由跳转')
})
最后,向外暴露router
对象
export default router
三、router标签
路由参数传递
在当前路由组件,使用this.$route.params.占位符变量
获取路由占位符的数据
<router-link>
的to
属性可以是对象{path:'/home',query:{name:'zhangsan'}}
携带query参数路由/?name=zhangsan
使用 this.$route.query
获取query的参数数据
router-view & router-link
在App.vue
中的使用需要使用<router-view>
来展现路由的页面,<router-link>
来实现路由切换
<router-link>
中的属性:
-
to = "/home"
跳转到/home
的位置 -
tag = "button"
把<router-link>
渲染成button
标签,默认是a
标签 -
replace
使用replace
的方式不会留下history记录,不能用浏览器前进后退,默认是push
的方式 -
active-class = "active"
元素处于活跃状态下的样式类class
为active
,默认样式类是router-link-active
keep-alive
keep-alive
会缓存页面,不会重复的创建销毁,两个属性:
-
include="组件name,..."
正则或字符串 对某些组件进行缓存 -
exclude="组件name,..."
正则或字符串 排除某些组件不进行缓存
被keep-alive
包裹router-view
的route
才会触发activated
、deactivated
生命周期的回调
<keep-alive>
<router-view/>
</keep-alive>
使用代码跳转路由
main.js
//main.js
import Vue from 'vue'
import App from './App'
import router from 'src/router'
new Vue({
el:'#app',
router,
render: h => h(App)
data: {},
components: {},
methods: {},
computed: {},
watch: {}
})
App.vue
//App.vue
<template>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
<button @click="tohome">Home(代码方式)</button>
<router-view></router-view>
</template>
<script>
export default {
name: 'App',
data() {
return {} //子组件的data必须用工厂函数返回
},
components: {},
methods: {
tohome() {
this.$router.push('/home') //push方式
//this.$router.replace('/home') //replace方式
}
},
computed: {}
}
</script>
<style scoped>
</style>