vue-router
动态路由
在设置路由映射关系时:后面使用:添加拼接内容
{
path:'/user/:userId',
component:User
}
在使用时:动态获取userId的内容,使用v-bind,然后进行字符串拼接
<router-link v-bind:to="'/user/'+userId">用户</router-link>
data(){
return {
userId:123,
}
}
就可以实现动态路由
获取动态添加内容,添加到User.vue中,获取userId内容
computed:{
userId(){
return this.$route.params.userId
//this.$router获取router对象
//this.$route获取活跃的路由
//params表示参数,userId是因为在router配置映射时用的userId
}
}
路由懒加载
vue-router打包文件解析
路由懒加载的使用
由于业务代码比较大,所以上图的第一个js文件比较大,文件一次请求过来时间比较长,导致界面空白。
懒加载:用到时再加载
如果把不同路由对应的组件分割成不同的代码块,当路由被访问时才加载对应的组件,这样变得高效,用户不会出现短暂空白。
路由懒加载:将路由对应的组件打包成一个个的js代码块,访问时才加载对应的组件。
懒加载的使用:结合ES6语法
{
path:'/home',
component:() => import ('../components/Home'),
},
或者
const Home = () => import ('../components/Home')
{
path:'/home',
component:Home,
},
之后使用时都需要使用懒加载,以下对应三个路由
嵌套路由
路由配置
{
path:'/home',
component:Home,
children:[
{
path:'',
redirect:'news'
},
{
path:'news',
component:News,
},
{
path:'message',
component: Message,
}
]
},
路由使用(在Home.vue中)
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">消息</router-link>
<router-view></router-view>
router-link传递参数
配置动态路由——params
配置路由
{
path:'/user/:userId',
component:User
}
传递参数
<router-link v-bind:to="'/user/'+userId">用户</router-link>
data(){
return {
userId:123,
}
}
使用参数
1,使用computed
computed:{
userId(){
return this.$route.params.userId
//this.$router获取router对象
//this.$route获取活跃的路由
//params表示参数,userId是因为在router配置映射时用的userId
}
}
2,直接使用
<h3>{{$route.params.userId}}</h3>
使用query
url:协议://服务器地址:端口/路径?查询
protocol : // hostname[:port] / path / [;parameters][?query]#fragment
parameters(参数)fragment(信息片断)
传递参数
<router-link v-bind:to="{
path:'/profile',
query:{name:'hjf',age:18}
}">我的</router-link>
使用参数
<h3>{{$route.query.name}}</h3>
<h3>{{$route.query.age}}</h3>
button传递参数
使用query
<button @click="profileClick">我的</button>
<router-view/>
profileClick(){
this.$router.push({
path:'/profile',
query:{
name:'hjf',
age:14
}
})
<h3>{{$route.query.name}}</h3>
<h3>{{$route.query.age}}</h3>
使用params
<button @click="userClick">用户</button>
userClick(){
this.$router.push('/user/'+this.userId);
}
<h3>{{$route.params.userId}}</h3>