Reusing small bits of markup inside a component in a vue file

Viewed 193

I am just starting to learn Vue and while doing a very basic template I found myself repeating small bits of HTML / components in the same template because of a v-if and different containing components depending on its result.

Though I have solved this repeating the same lines a few times I find it less than ideal and would like to know if there is a better way to make it DRY (without having to create a new component).

I would like to be able to reuse the following lines:

{{ item.name }}
And a bit more of markup, but not much and no "functionality"

Definitively creating a new vue file with a new component would be overkill. But having to repeat those lines (the real ones a little bit more complex) really gives me pain a little bit.

Here is a very simple example that illustrates the problem.

Please remember that this is not the real code, the real code is inside a vue file (but I do not know how to simulate this here or in codepen)!!

var app = new Vue({
  el: '#app',
  data: {
    items: [
      {
        name: 'name 1',
        link: 'http://www.google.com'
      },
      {
        name: 'name 2',
        link: ''
      },
    ]
  },
  methods: {
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js"></script>
<div id="app">
  <template v-for="item in items">
    <a :href="item.link" v-if="item.link != ''">
      {{ item.name }}<br>
      And a bit more of markup, but not much and no functionality
    </a>
    <p v-else>
      {{ item.name }}<br>
      And a bit more of markup, but not much and no functionality
    </p>
  </template>
</div>

1 Answers

You can use a component with "is" property set to the tag type you want rendered:

<div id="app">
  <template v-for="item in items">
    <component :href="item.link || false" :is="item.link ? 'a' : 'p'">
      {{ item.name }}<br>
      And a bit more of markup, but not much and no functionality
    </component>        
  </template>
</div>

false on href causes that attr to not be rendered at all

Related