neubert
neubert

Reputation: 16832

defining derived variables from for loops

Here's my markup:

<ul id="example-1">
  <li v-for="item in items" :key="item.message">
    <span :style="item.message.substr(-1) == '*' ? 'color: green' : ''">
      {{ item.message }}
    </span>
    <span v-if="item.message.substr(-1) == '*'">
      (special!)
    </span>
  </li>
</ul>

Here's my JS:

var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo *' },
      { message: 'Bar' }
    ]
  }
})

In this code I'm doing item.message.substr(-1) == '*' twice. What I'd like to be able to do is to assign item.message.substr(-1) == '*' to a variable. eg. isSpecial or some such. Then I could do the following:

My question is... how do I do this?

Normally, for new variables, you'd use the data property in the Vue constructor parameter. But that doesn't work if you're in a v-for so idk what my alternative is (if there even is one).

Here's the JS fiddle:

https://jsfiddle.net/r810xmbq/

Upvotes: 0

Views: 37

Answers (2)

Radu Diță
Radu Diță

Reputation: 14201

Try to use a computed property to map your array

var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo *' },
      { message: 'Bar' }
    ]
  },
  computed: {
     computedItems() {
        return this.items.map(item => {
          return Object.assign({}, item, {isSpecial: item.message.substr(-1) == '*'})
        })
     }
  }
})

Using Object.assign ensures that you don't alter the original array. And update your template

<ul id="example-1">
  <li v-for="item in computedItems" :key="item.message">
    <span :style="item.isSpecial ? 'color: green' : ''">
      {{ item.message }}
    </span>
    <span v-if="item.isSpecial">
      (special!)
    </span>
  </li>
</ul>

Here's a working fiddle

Upvotes: 1

Igor Moraru
Igor Moraru

Reputation: 7739

You can use a computed property, to map the value of item.message.substr(-1) == '*' to a new object property.

computed: {
 mappedArray(){
   return this.items.map(item => {
    item['isSpecial'] = item.message.substr(-1) == '*'
    return item
   })
}

Upvotes: 1

Related Questions