【问题标题】:How to set index/key value to 1 rather 0如何将索引/键值设置为 1 而不是 0
【发布时间】:2017-08-10 06:11:23
【问题描述】:

有没有办法将 index 设置为 1 而不是 0,因为在我的代码中的大多数地方使用 index+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>

【问题讨论】:

  • 索引始终从零开始。您将 1 添加到索引的方法可以正常工作。另外,请参阅讨论:stackoverflow.com/questions/2826682/…
  • 使用 val 代替索引? vuejs.org/v2/guide/list.html#Range-v-for
  • @Bert,这项工作,我觉得很愚蠢 :) 如果您想发布您的建议,我可以将您的建议标记为答案。我刚刚做了这个更改&lt;option :value="val" v-for="val in 12"&gt; {{val}} Month{{ fnPluralize(val) }} {{ fnInsertIndent(val) }} ${{perMonth * (val)}} &lt;/option&gt;

标签: javascript vuejs2


【解决方案1】:

当您使用range v-for 时,value 从一开始,而索引从零开始。

因此,在您的情况下,只需使用该值。

console.clear()


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多