zoukankan      html  css  js  c++  java
  • route路由组件传递参数

    在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。

    使用 props 将组件和路由解耦:

    取代与 $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 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 被设置为 trueroute.params 将会被设置为组件属性。

    对象模式

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

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

    函数模式

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

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

    URL /search?q=vue 会将 {query: 'vue'} 作为属性传递给 SearchUser 组件。

    请尽可能保持 props 函数为无状态的,因为它只会在路由发生变化时起作用。如果你需要状态来定义 props,请使用包装组件,这样 Vue 才可以对状态变化做出反应。

  • 相关阅读:
    挂载磁盘不成功显示mount: /mnt: wrong fs type, bad option, bad superblock..............
    Linux如何查看文件的创建、修改时间?
    Linux,Centos下 Tomcat8 修改jvm内存配置的新方法
    ActiveMQ问题分析和解决
    centos如何删除文件夹
    CentOS 几种重启方式的区别
    CentOS查看文件夹大小
    挂在光盘出现写保护mount: block device /dev/sr0 is writeprotected, mounting readonly
    centos7安装activeMq
    Rust中的workspace
  • 原文地址:https://www.cnblogs.com/instead-everyone/p/14571116.html
Copyright © 2011-2022 走看看