vue-router路由组件传参解耦

这里写自定义目录标题

 

vue-router路由组件传参解耦

路由组件中使用$route取路由参数会导致该路由与该组件形成高度绑定耦合

原始取参方式

// 路由组件
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
//路由定义
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

props解耦

 

// 路由组件
const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const Sidebar = {
  props: ['id'],
  template: '<div>Sidebar {{ id }}</div>'
}
//路由定义
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 props 选项:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

 

布尔模式

如果 props 被设置为 true,route.params 将会被被定义在组件的props中

对象模式

如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。

// 路由组件
const Promotion= {
  props: ['info'],
  template: '<div>Sidebar {{ info}}</div>' // 结果  111
}
//路由定义
const router = new VueRouter({
  routes: [
    { path: '/promotion/from-newsletter', component: Promotion, props: { info: 111} }
  ]
})

函数模式

你可以创建一个函数返回 props。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等

 

// 输入的导航路由/search/1900

// 路由组件
const SearchUser= {
  props: ['name'],
  template: '<div>SearchUser{{ name}}</div>' // 结果  2019--1900!
}
//路由定义
const router = new VueRouter({
  routes: [
    { path: '/search/:years', component: SearchUser, props: dynamicPropsFn  }
  ]
})

function dynamicPropsFn (route) {
  const now = new Date()
  return {
    name: `${now.getFullYear()}--${parseInt(route.params.years)}!`
  }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值