2👍
✅
You need to define a prop inside the component, value that you are gone pass in to the it. In this particular case I call it type, then you can add more types without adding more props.
Vue.component('AppPage', {
props: {
type: {
type: String,
required: true
}
},
template: `
<div :class="type"><slot /></div>
`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<app-page type="table">table</app-page>
<app-page type="flex">flex</app-page>
1👍
You can simply pass props to AppPage
but just need to declare the type of the prop as Boolean
. This will automatically set the passed prop to true
and other props to false.
Then you can update your template to dynamically set the class and render based on passed prop value like:
<div v-if="table || flex" :class="{'table': table, 'flex': flex}">
<slot></slot>
</div>
Working Demo:
Vue.component('app-page', {
props: {
table: Boolean,
flex: Boolean
},
template: `
<div v-if="table || flex" :class="{'table': table, 'flex': flex}">
<slot></slot>
</div>
`
})
new Vue({el: "#myApp"})
.table {padding: 4px 8px; border: 1px solid green; margin: 5px;border-radius: 4px;}
.flex {padding: 4px 8px; border: 1px solid orange; margin: 5px;border-radius: 4px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
<app-page table>one item</app-page>
<app-page flex>two item</app-page>
<app-page table>test item</app-page>
</div>
Source:stackexchange.com