官方介绍:Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
用大白话讲,vue-router主要用于构建单页面应用。详细查看官方文档 vue-router使用指南
‘/home’路径下有’/home/news’资源,即请求子组件下面子组件。
const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const route = {
{
path:'/home',
component:Home,
meta:{
title:'首页'
},
children:[
{
path: '',
redirect:'/home/news'
},
{
path:'news',
component:HomeNews
},
{
path:'message',
component:HomeMessage
}
]
}
}
方式一:params
路由格式:path: ‘/user/:userId’
访问路由并传参
<router-link :to="'/user/' + userId"><button>用户button>router-link>
接收参数 $route.params.userId,$route对象它封装了当前活动的路由。
方式二:query
路由格式(普通路由):path:’/profile’
访问路由并传递参数
<router-link :to="{path:'/profile',query:{id:1,name:'邹越鹏',age:19}}"><button>档案button>router-link>
接收参数使用$route.query.id。
先来看看我们普通的导入方式(不推荐使用),用户请求时会自动下载所有相关的组件资源,是EAGER的。
//导入组件
import Home from '../components/Home'
使用懒加载的方式导入,只有需要该资源的时候就会下载,是Lazy的。
const Home = () => import('../components/Home')
keep-alive用于保存一个组件的状态,使其不必每次重新渲染,可用于记住我们浏览的某些状态。
创建组件Home,下面案例用于保存Home组件message或news的状态。
<template>
<h2>我是首页h2>
<router-link to="/home/news"><button>新闻button>router-link>
<router-link to="/home/message"><button>消息button>router-link>
<router-view>router-view>
template>
<script>
// import {} from 'vue'
export default {
name: "Home",
data(){
return{
message:'你好啊',
path:'/home/news'
}
},
created(){
console.log('Home created')
},
//以下两个函数只有在其组件被keep-alive标签保持的时候才会触发
activated() {//当前路由活动时调用
console.log('Home active')
this.$router.push(this.path)
// console.log('Home active')
},
// deactivated() {//当前路由失效,退出时调用
// console.log('Home deactivated')
// },
beforeRouteLeave(to,from){
console.log('beforeRouteLeave')
this.path = this.$route.path;
}
}
script>
<style scoped>
style>
路由配置
path:'/home',
component:Home,
meta:{
title:'首页',
keepAlive:true
},
children:[
{
path: '',
redirect:'/home/news'
},
{
path:'news',
component:HomeNews
},
{
path:'message',
component:HomeMessage
}
]
keep-alive配合router-view的用法
<router-view v-slot="{Component}">
<component :is="Component" v-if="!this.$route.meta.keepAlive"/>
<keep-alive include="Home">
<component :is="Component" v-if="this.$route.meta.keepAlive"/>
keep-alive>
router-view>