Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment variable in template v-for loop

Tags:

vue.js

vuejs2

I have such pseudo-vue-js loop:

var j = 0;
for(var i = 0; i < 100; i ++){
    <item-component></item-component>

    if(i % 10 === 0){
        <component :is="'advertising-block-' + j"></component>
        j ++;
    }
}

How to override it to vue template?

I need to show different advertising block after each tenth items and name of such component (block) should be:

advertising-block-0
advertising-block-1
...
advertising-block-10 (last one after 100th item).
like image 248
webprogrammer Avatar asked Jun 30 '26 07:06

webprogrammer


1 Answers

You can use v-for to iterate 100 times, and after every tenth item show an advertising component (this should be a common one that takes j and show the corresponding item) using v-if:

const itemcomponent = Vue.component('itemcomponent', {
  template: '#itemcomponent',
});
const advertisingblock = Vue.component('advertisingblock', {
  template: '#advertisingblock',
  props: ['id']
});

new Vue({
  el:"#app",
  components: { itemcomponent, advertisingblock }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template id="itemcomponent">
  <div>item</div>
</template>

<template id="advertisingblock">
  <div>advertising-block-{{id}}</div>
</template>

<div id="app">
  <div v-for="i in 100">
    <div><itemcomponent/></div>
    <div v-if="i%10===0"><advertisingblock :id="i/10"/></div>
  </div>
</div>
like image 172
Majed Badawi Avatar answered Jul 02 '26 06:07

Majed Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!