Reputation: 103
good afternoon, I'm practicing with vue, how can I make a for loop return me word by word plus the previous one.
<div v-for="option in this.options.split(' ')" :key="tag" >
<h2>{{option}}</h2>
</div>
data() {
return {
options:'the green house'
}
},
and now returns
the
green
house
and I would like you to return
the
the green
the green house
how can I do it?
Upvotes: 1
Views: 40
Reputation: 28424
You can create a computed
property that returns the expected list as follows:
new Vue({
el:"#app",
data: () => ({ options: 'the green house' }),
computed: {
myOptions() {
const list = this.options.split(' ');
return list.map((option, i) => list.slice(0, i+1).join(' '));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(option, index) in myOptions" :key="index">
<h2>{{option}}</h2>
</div>
</div>
Upvotes: 1
Reputation: 25659
You should create a computed
property to avoid cluttering your template with logic. Then, you can use split
, map
, slice
and join
.
Demo:
new Vue({
el: '#app',
data() {
return { options: 'the green house' };
},
computed: {
optionsArray() {
return this.options.split(' ')
.map((_, i, arr) => arr.slice(0, i + 1).join(' '));
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>
<div id="app">
<div>
<div v-for="option in optionsArray" :key="option">
<h2>{{option}}</h2>
</div>
</div>
</div>
Upvotes: 4