0

I'm trying to keep all text in one tag when looping through an array of split up text

<template v-for="message in array">
     <span v-if="some condition">
          <a href="">{[ message }}</a>
     </span>
     <span v-else>
          {{ message }}
     </span>
</template

This renders span over and over like this:

<span>Text</span>
<span><a href="">link</a></span>
<span>text again</span>

How do I make it so it's just like this:

<span>Text <a href="">link</a> text again</span>

1 Answer 1

0

Similar to what you have done for the v-for, you can use <template> element for v-if and v-else binding as well. They will not be added to DOM.

For example, I've modified your view slightly to show how it works:

var app = new Vue({
  el: "#app",
  data: {
    array: [
      {
        toggle: true,
        txt: "Abc"
      },
      {
        toggle: false,
        txt: "Def"
      }
    ]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>

<div id="app">
    <span>
    <template v-for="message in array">
    
       <template v-if="message.toggle">
            <a href="">{{ message.txt }}</a>
       </template>
       <template v-else>
            {{ message.txt }}
       </template>
    
    </template>
    </span>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I tried that. But now it seems it's performing a line break per text?
my bad it was my CSS that was causing the break for the a tag!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.