2017-08-10 87 views
0

有沒有辦法將索引設置爲1而不是0,因爲它有點傷害我在我的代碼中的大部分位置使用索引+ 1。如何設置索引/鍵值爲1而不是0

Vue.component('BuySubscription', { 
 
    template: '#buy-subscription', 
 
    data() { 
 
    return({ 
 
     perMonth: 19, 
 
     selectedSubscription: 0 
 
    }) 
 
    }, 
 
    methods: { 
 
    fnSelectedSubscription() { 
 
     console.log('you have selected:' + this.selectedSubscription * this.perMonth); 
 
    }, 
 
    fnPluralize(i) { 
 
     return (i > 0) ? 's': '' 
 
    }, 
 
    fnInsertIndent(i) { 
 
     i = i+1; 
 

 
     if (i === 1) { 
 
     return '........................' 
 
     } else if(i <= 9) { 
 
     return '......................' 
 
     } else if (i <= 12){ 
 
     return '....................' 
 
     } 
 
    } 
 
    } 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> 
 

 
<div id="app" class="col-lg-6 d-flex align-items-center"> 
 
    <buy-subscription></buy-subscription> 
 
</div> 
 

 
<script type="text/x-template" id="buy-subscription"> 
 
    <div> 
 
    <p>Please select subscription to purchase.</p> 
 
    <div class="form-group"> 
 
     <select class="form-control" v-model="selectedSubscription"> 
 
     <option value="0" selected>Select Subscription...</option> 
 
     <option :value="index+1" v-for="(val, index) in 12"> 
 
      {{index+1}} Month{{ fnPluralize(index) }} {{ fnInsertIndent(index) }} ${{perMonth * (index+1)}} 
 
     </option> 
 
     </select> 
 
    </div> 
 
    <h1 class="text-center">${{selectedSubscription * perMonth}}.00</h1> 
 
    <button class="btn btn-warning btn-block" 
 
      :class="{disabled: selectedSubscription <= 0}" 
 
      @click="fnSelectedSubscription"> 
 
     Buy now with <i>PayPal</i> 
 
    </button> 
 
    </div> 
 
</script>

+2

指數始終是從零開始的。您向索引中添加1的方法可以很好地工作。另請參閱討論:https://stackoverflow.com/questions/2826682/how-do-i-create-an-array-in-javascript-whose-index-starts-from-1 – Terry

+1

使用val而不是索引? https://vuejs.org/v2/guide/list.html#Range-v-for – Bert

+0

@Bert,這項工作,我覺得很愚蠢:)如果你想發佈你的答案,我可以將你的建議標記爲答案。我只是做了這樣的改變: {{val}} Month {{fnPluralize(val)}} {{fnInsertIndent(val)}} $ { perMonth *(val)}} ' – Syed

回答

1

當您使用range v-forvalue從1開始,而該指數是從零開始的。

因此,在你的情況下,只需使用該值。

console.clear() 
 

 

 
new Vue({ 
 
    el:"#app" 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="app"> 
 
    <div v-for="val, index in 10">Value: {{val}}, Index: {{index}}</div> 
 
</div>