Reputation: 287
Hello, how can i use these empty props (attributes) in VUE component?
I have this HTML: app-page is component name
<app-page table>one item</app-page>
<app-page flex>two item</app-page>
<app-page table>test item</app-page>
One VUE component
<script>
export default {
name: "AppPage",
template: `
<div :is="table" class="table">
<slot></slot>
</div>
<div :is="flex" class="flex">
<slot></slot>
</div>
`
};
</script>
I want render it like this
<div class="table">one item</div>
<div class="flex">two item</div>
<div class="table">test item</div>
I haven't worked with VUE for a long time, so I forgot about this a bit.
Upvotes: 0
Views: 125
Reputation: 19158
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>
Upvotes: 2
Reputation: 73936
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>
Upvotes: 1