7、路由组件传参

介绍

学习vue-router的一些学习笔记,所有笔记内容请看 vue-router学习笔记

布尔模式

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

如上述所示,在组件中直接使用$route,会与当前的路由形成高度耦合,则组件User就只能在此URL上使用,不能进行复用。
通过使用props进行解耦:

const User={
    props:['id'],
    template:'<div>Uer{{ id }}</div>'
}
const router = new VueRouter({
    routes:[
        {
            path:'/user/:id',
            component:User,
            props:true
        }
        // 对于包含命名视图的路由,必须为每个命名视图添加props选项
        {
            path:'/user/:id',
            components:{
                default:User,
                siderBar:Siderbar
            },
            props:{
                default:true,
                siderBar:false
            }
        }
    ]
})

对象模式

如果props是一个对象时,它会被原样设置为组件的属性**,只有当路由是静态路由时才起作用**,即path中没有动态路径参数 。

const router=new VueRouter({
    routes:[
        {
            path:'/promotion/from-newsletter',
            component:Promotion,
            props:{ newsletterPopup: false}
        }
    ]
})

函数模式

可以创建一个函数返回props,这样可以将参数转换成另一种类型,将静态值与其路由的值结合起来等:

const router = new VueRouter({
    path:'/search',
    component:SearchUser,
    props:(route)=>{
        {query:route.query.q}
    }
})

上述props的作用,是将/search?q=vue中的q=vue转换成对象{ query : vue },作为属性传递给SearchUser 组件。

具体示例:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Hello from './Hello.vue'

Vue.use(VueRouter)

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

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/', component: Hello }, // No props, no nothing
    // 动态路由,props传递route.param到组件
    { path: '/hello/:name', component: Hello, props: true }, // Pass route.params to props
    // 静态路由,props传递对象到组件
    { path: '/static', component: Hello, props: { name: 'world' }}, // static values
    { path: '/dynamic/:years', component: Hello, props: dynamicPropsFn }, // custom logic for mapping between route and props
    { path: '/attrs', component: Hello, props: { name: 'attrs' }}
  ]
})

new Vue({
  router,
  template: `
    <div id="app">
      <h1>Route props</h1>
      <ul>
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/hello/you">/hello/you</router-link></li>
        <li><router-link to="/static">/static</router-link></li>
        <li><router-link to="/dynamic/1">/dynamic/1</router-link></li>
        <li><router-link to="/attrs">/attrs</router-link></li>
      </ul>
      <router-view class="view" foo="123"></router-view>
    </div>
  `
}).$mount('#app')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值