The v-for tag in vue is great, no doubt.
I have now the situation where I want to generate a description list such as this. In this case I need to generate two DOM elements for each element in my array:
<dl class="row">
<dt class="col-sm-3">Description lists</dt>
<dd class="col-sm-9">A description list is perfect for defining terms.</dd>
Is there any (more or less elegant) way to do this with vue?
The v-for tag in vue is great, no doubt.
I have now the situation where I want to generate a description list such as this. In this case I need to generate two DOM elements for each element in my array:
<dl class="row">
<dt class="col-sm-3">Description lists</dt>
<dd class="col-sm-9">A description list is perfect for defining terms.</dd>
Is there any (more or less elegant) way to do this with vue?
Share Improve this question asked Jul 28, 2019 at 11:23 Peter T.Peter T. 3,3255 gold badges37 silver badges45 bronze badges3 Answers
Reset to default 10You could use the <template>
tag with v-for
to render a block of multiple elements
new Vue({
el: "#app",
data() {
return {
items: [
{ short: "1", long: "Long Description 1" },
{ short: "2", long: "Long Description 2" },
{ short: "3", long: "Long Description 3" },
{ short: "4", long: "Long Description 4" },
]
}
}
})
<link href="https://stackpath.bootstrapcdn./bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<dl class="row">
<template v-for="data in items">
<dt class="col-sm-3">{{data.short}}</dt>
<dd class="col-sm-9">{{data.long}}</dd>
</template>
</dl>
</div>
The HTML5 specification (according to MDN) allows for wrapping <dt>
and <dd>
elements in a <div>
for microdata or styling purposes. I'd remend the following:
<dl class="row">
<div v-for="item in items" :key="item.id">
<dt class="col-sm-3">{{ item.key }}</dt>
<dd class="col-sm-9">{{ item.value }}</dd>
</div>
</dl>
This also handles the v-for requires a :key attribute.
You can use <template v-for="item in items"></template>
which will only render the contents in your HTML and not a wrapping element. So you can generate two DOM elements for each element in an array.
Example :
<template v-for="item in items">
<dl class="row">
<dt class="col-sm-3">Description lists</dt>
<dd class="col-sm-9">A description list is perfect for defining terms.</dd>
</dl>
<dl class="row">
<dt class="col-sm-3">Description lists</dt>
<dd class="col-sm-9">A description list is perfect for defining terms.</dd>
</dl>
<template>