Passing props to Vue.js components instantiated by Vue-router

风格不统一 提交于 2019-11-26 09:46:41

问题


Suppose I have a Vue.js component like this:

var Bar = Vue.extend({
    props: [\'my-props\'],
    template: \'<p>This is bar!</p>\'
});

And I want to use it when some route in vue-router is matched like this:

router.map({
    \'/bar\': {
        component: Bar
    }
});

Normally in order to pass \'myProps\' to the component I would do something like this:

Vue.component(\'my-bar\', Bar);

and in the html:

<my-bar my-props=\"hello!\"></my-bar>

In this case, the router is drawing automatically the component in the router-view element when the route is matched.

My question is, in this case, how can I pass the the props to the component?


回答1:


<router-view :some-value-to-pass="localValue"></router-view>

and in your components just add prop:

props: {
      someValueToPass: String
    },

vue-router will match prop in component




回答2:


sadly non of the prev solutions actually answers the question so here is a one from quora

basically the part that docs doesn't explain well is

When props is set to true, the route.params will be set as the component props.

so what you actually need when sending the prop through the route is to assign it to the params key ex

this.$router.push({
    name: 'Home',
    params: {
        theme: 'dark'
    }
})

so the full example would be

// component
const User = {
  props: ['test'],
  template: '<div>User {{ test }}</div>'
}

// router
new VueRouter({
  routes: [
    { 
      path: '/user',
      component: User,
      name: 'user',
      props: true 
    }
  ]
})

// usage
this.$router.push({
    name: 'user',
    params: {
        test: 'hello there' // or anything you want
    }
}) 



回答3:


In the router,

const router = new VueRouter({
  routes: [
    { path: 'YOUR__PATH', component: Bar, props: { authorName: 'Robert' } }
  ]
})

And inside the <Bar /> component,

var Bar = Vue.extend({
    props: ['authorName'],
    template: '<p>Hey, {{ authorName }}</p>'
});



回答4:


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

        // for routes with named views, you have to define the props option for each named view:
        {
          path: '/user/:id', 
          components: { default: User, sidebar: Sidebar },
          props: { default: true, sidebar: false }
        }
      ]
    })

Object mode

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

That is the official answer. link




回答5:


Use:

this.$route.MY_PROP

to get a route prop



来源:https://stackoverflow.com/questions/37937262/passing-props-to-vue-js-components-instantiated-by-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!