Vue动态路由

1.、动态匹配路由的基本用法

应用场景:通过动态路由参数的模式进行路由匹配

var router = new VueRouter({
    routers:[
        //动态路径参数 以冒号开头
        {
            path:'/path/:id'
            component:User
        }
    ]
})

const User = {
    //路由组件中通过$route.params.id获取路由参数
    template:'<div>User{{$route.params.id}}</div>'
}

2、路由组件传递参数

$route与对应路由形成高度耦合,不够灵活,所以可以使用props将组件和路由解耦

2.1、props的值为布尔类型

  const router = new VueRouter({
    routes: [
      // 如果 props 被设置为 true,route.params 将会被设置为组件属性
      { path: '/user/:id', component: User, props: true }
    ]
  })

  const User = {
    props: ['id'], // 使用 props 接收路由参数
    template: '<div>用户ID:{{ id }}</div>'  // 使用路由参数
  }

2.2、props的值为对象类型

  const router = new VueRouter({
    routes: [
      // 如果 props 是一个对象,它会被按原样设置为组件属性
      { path: '/user/:id', component: User, props: { uname: 'lisi', age: 12 }}
    ]
  })

  const User = {
    props: ['uname', 'age'],
    template: ‘<div>用户信息:{{ uname + '---' + age}}</div>'
  }

 2.3、props的值为函数类型

  const router = new VueRouter({
    routes: [
      // 如果 props 是一个函数,则这个函数接收 route 对象为自己的形参
      { path: '/user/:id', 
        component: User, 
        props: route => ({ uname: 'zs', age: 20, id: route.params.id })}
    ]
  })

  const User = {
    props: ['uname', 'age', 'id'],
    template: ‘<div>用户信息:{{ uname + '---' + age + '---' + id}}</div>'
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈善强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值