vuejs学习5.3 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值