Is it possible to pass a component as props and use it in a child Component in Vue?

后端 未结 4 1573
萌比男神i
萌比男神i 2020-12-02 16:29

In a Vue 2.0 app, let\'s say we have components A, B and C.

A declares, registers and uses B

Is it possible to pass C from A to B?

Something like this:<

4条回答
  •  鱼传尺愫
    2020-12-02 17:27

    Here's solution to forward custom component through props of another component

    :is is special attribute and it will be used to replace your actual component and it will be ignored if you try to use it as a prop in your component. Luckily you can use something else like el and then forward this to component like so:

    
    
    

    Any valid element you use in el attribute will be used as a child component. It can be html or reference to your custom component or div by default as specified in component declaration.

    Passing custom component to prop is little bit tricky. One would assume you declare in a components property of parent component and then use it for el attribute but this doesn't work. Instead you need to have your dynamic component in data or computed property so you can use it in a template as a prop. Also note AnotherComponent doesn't need to be declared in components property.

    
    
    
    

    Using computed property for your dynamic component allows you to switch between components easily:

    
    

    Increase this.count to alternate between AnotherComponent and simple article html element.

提交回复
热议问题