12

I am rendering a list of store titles in VueJS, some of them have a url property, some of them don't. If the title has a url, I want to add a a href property:

<div v-for="(store, index) in stores">
  <span v-if="store.link"><a :href="store.link" target="_blank">{{ store.title }}</a></span>
  <span v-else="store.link">{{ store.title }}</span>
</div>

This works, but the code looks duplicated. Is there anyway to simplify the code further?

3 Answers 3

22

you can use component tag:

var app = new Vue({
  el: '#app',
  data () {
    return {
      stores: [
        {title:'product1',link:'/products/222'},
        {title:'product2'},
        {title:'product3',link:'/products/333'},
        {title:'product4'}
      ]
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div v-for="(store, index) in stores">
    <component :is="store.link?'a':'span'" :href="store.link || ''" target="_blank">{{store.title}}
    </component>
  </div>
</div>

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

Comments

6

I'd remove the first span element, as it's not necessary. Also, the v-else does not need the conditional statement (it's not v-else-if):

new Vue({
  el: '#app',
  data: {
    stores: [
      { link: 'foo', title: 'foo-text' },
      { title: 'bar-text' } 
    ]
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(store, index) in stores" :key="index">
    <a v-if="store.link" :href="store.link" target="_blank">{{ store.title }}</a>
    <span v-else>{{ store.title }}</span>
  </div>
</div>

Comments

0

You can use dynamic arguments in vue3 https://v3.vuejs.org/guide/template-syntax.html#dynamic-arguments

<a v-bind:[attributeName]="url"> ... </a>

or binding an object of attributes

<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.