简体   繁体   中英

What's the idiomatic way to pass component prop to a component in Vue.js?

I came from the ReactJS world that has a common way to create flexible components: pass components as prop to other component.

For example:

import MyCard from './MyCard';
import Slider from './Slider';

const Example = ({items}) => {
  return <div classname="example"> <Slider cardComponent={MyCard} items={items}/> </div>
}

Simple, elegant, clever.

What's the right and idiomatic way to realize this approach in Vue.js?

I don't need an answer how to create Slider component, I want to know what is the idiomatic way to pass MyCard component to it.

Depends on how you create your Slider component, does it take the path to the component, does it take the component, does it evaluate its children based on passed props, does it have slots, mixins?

My guess to this is:

*.html

<template id="example-template">
  <div class="example">
    <slider :items="items">
      <template #cardSlot="{requiredAttr1, requiredAttr2}">
        <my-card :attr1="requiredAttr1" :attr2="requiredAttr2">
      </template>
    </slider>
  </div>
</template>

*.js

import MyCard from './MyCard';
import Slider from './Slider';
export default {
  template: '#example-template',
  name: "Example",
  props: ["items"],
  components: {
    MyCard,
    Slider
  }
}

Slots

//slider component
<div class="slider"">
    <slot 
        name="slotname" 
        :passedPropName="sliderValue"
     >
    </slot>
</div>

//extended slider component
<slider>
    <template 
        #slotname="passedPropObj"
    >
        <mycomp 
           :propName="passedPropObj.passedPropName" 
        /> 
    </template>
</slider>

Dynamic & Async Components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM