2017-08-10 1 views
0

インデックスを1に設定する方法はありますか?コード内のほとんどの場所でインデックス+ 1を使用するのがちょっと難しいです。インデックス/キー値を1に設定する方法

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、その仕事、私はとてもばかげている:)私はあなたの投稿をしたい場合は、答えとして提案をマークすることができます。私はちょうどこの変更を行いました。 '' option:value = "val" v-for = "val in 12"> {{val}}月{{fnPluralize(val)}} {{fnInsertIndent(val)}} $ {{ perMonth *(val)}} ' – Syed

答えて

1

あなたがrange v-forを使用し、1でvalue開始、インデックスはゼロベースである一方で。

あなたの場合は、値をそのまま使用してください。

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>

関連する問題