Routing component parameter passing

Routing component parameter passing

Used in the assembly  $route causes the formation of their corresponding routing highly coupled, so that the assembly can only be used on certain URL, limit its flexibility.

Use  props the routing and decoupling components:

Substituted and  $route coupled

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

By  props decoupling

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 }
    }
  ]
})

This way you will be able to use any of the components in place, making it easier to reuse the assembly and testing.

# Boolean mode

If  props is set  true, route.params it will be set to the component properties.

# Object Model

If  props an object, it is provided as is to the component properties. When the  props static time is useful.

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

# Function mode

You can create a function return  props. This way you will be able to convert into another type of parameters, the combined value of a static value based routing, and so on.

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

URL  /search?q=vue will be  {query: 'vue'} passed as an attribute to the  SearchUser assembly.

Please keep as  props a function of stateless, because it will only work when route changes. If you need to define the status  props, use packaging components, such Vue can react to state changes.

For more advanced uses, see examples .

Published 349 original articles · won praise 493 · Views 1.93 million +

Guess you like

Origin blog.csdn.net/starzhou/article/details/104903195