Wrap element using v-if, otherwise just have content itself

vue.js

Solution

You can use `v-html` for example and render your logic inside a function:

function wrapSpan(el, link) { // link wrapper function
  return `<a href="${link}">${el}</a>`;
}

new Vue({
  el: '#app',
  data: {
    events: [
      {name: "Foo"},
      {name: "Bar", url: "google.com"}
    ]
  },
  methods: {
    element: function(i) {
      const name = this.events[i].name;
      const url = this.events[i].url || null;
      const span = `<span style="color: green">${name}</span>`; // long span
      return (url) ? wrapSpan(span, url) : span;
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <div v-for="(event, index) in events">
    <span v-html="element(index)"></span>
  </div>
</div>

Problem

I have a set of elements being generated in a `v-for` directive that, if the object has a `url` property, get wrapped in an `<a>` tag - otherwise, I need it to just emit the element itself. For example, ``` var data = { events: [ {name: "Foo"}, {name: "Bar", url: "google.com"} ] }; ``` and the corresponding HTML: ``` <div v-for="event in events"> <span>{{event.name}}</span> </div> ``` What I need is to wrap the `<span>` in an `<a v-bind:href="url">` only if there is a `url` property present. I understand I could use a `v-if` and use two spans, such as: ``` <span v-if="!event.url">{{event.name}}</span> <a v-bind:href="event.url" v-if="event.url"> <span>{{event.name}}</span> </a> ``` However, in my use case the `<span>` element here could be massive and I don't want to repeat myself just to wrap the element. Is there a way to achieve a conditional wrap such as the above?

Original source

Related problems