Search code examples
javascriptvue.jsv-for

How can I generate a description list (dl) in Vue.js using v-for?


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?


Solution

  • You 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.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/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>