Props
Props are custom attributes that allow data to be passed to a child component. The child component can then use this data to alter what is displayed. However, to use the prop, the child component must declare it in the list of props using the props
option.
app.component('bs-button', {
props: ['variant'],
template: `
<button :class="'btn btn-' + variant">
<slot></slot>
</button>
`
})
<bs-button variant="primary">Primary Button</bs-button>
Generating Components from Array
When generating multiple child components from an array of data, the v-for
and v-bind
directives should be used. In addition, when using v-for
with a component, a special key
attribute should also be added to help Vue identify a specific component instance.
const app = Vue.createApp({
data: function () {
return {
buttons: [
{ variant: 'primary', text: 'Blue Button' },
{ variant: 'success', text: 'Green Button' },
{ variant: 'danger', text: 'Red Button' }
]
}
}
})
app.component('bs-button', {
props: ['variant'],
template: `
<button :class="'btn btn-' + variant">
<slot></slot>
</button>
`
})
<bs-button
v-for="(button, index) in buttons"
:key="index"
:variant="button.variant">
{{ button.text }}
</bs-button>