vue-router的组件传值

前言

路由传参都会涉及到路由配置项中的props

布尔模式的路由传参

正常情况下的传参通过在路由表中定义/:属性,在路由表对应的component中用$route.params.属性接收.这种传值方式有一个弊端,就是$route和路由形成了耦合,让组件只能在特定的路由上使用.如下,User组件的$route.params.id只能在path为/user/:id的url下使用.我们可以通过布尔模式来解决耦合性的问题

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

布尔模式下的解决方法就是给路由表中添加props:true.这样就可以在任何地方使用该组件了,方便了组件的复用

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: '/user/:id',
//components为多视图的时候要把props变为对象,单独定义每一个视图的props属性 components: {
default: User, sidebar: Sidebar }, props: { default: true, sidebar: false } } ] })

对象模式的路由传参

对象模式的路由传参时,props是静态内容才有用

<ul>
      <router-link tag="li" to="/position" active-class="active">职位</router-link>
</ul>
    <router-view></router-view>

const position = {
      props: ['id', 'username', 'age'],
      template: `<div>postion- {{username}}-{{age}}</div>`
    }

var router = new VueRouter({
      // mode: 'history',
      routes: [
        {
          path: '/position',
          component: position,
          props: { username: 'di', age: 20 }
        }
      ]
    })

    var vm = new Vue({
      router,
      el: '#app'
    })

效果

函数模式的路由传参

比较常用,props的值是一个函数,函数内部返回的是一个对象,对象的构成是key:route.query.问号后面的属性名

  <router-link tag="li" to="/search?keyword=di" active-class="active">搜索</router-link>
 
const search = { props: ['any'], template: `<div>search-{{any}}</div>` } var router = new VueRouter({ routes: [ { path: '/search', component: search, props: (route) => ({ any: route.query.keyword }) } ] }) var vm = new Vue({ router, el: '#app' })

 

原文地址:https://www.cnblogs.com/liuXiaoDi/p/13068275.html