Reputation: 16832
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:
<span :style="isSpecial ? 'color: green' : ''">
instead of <span :style="item.message.substr(-1) == '*' ? 'color: green' : ''">
<span v-if="isSpecial">
instead of <span v-if="item.message.substr(-1) == '*'">
.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
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
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