Home > other >  Using arrow function to initialize data() in Vue
Using arrow function to initialize data() in Vue

Time:02-25

Why I cannot get the array of 'expired'? I can see expired is a function, but I want a array.

export default {
  name: 'a',
  data () {
    return {
      labelEnable: "a",
      expired: () => {
        var a = []
        for (var i = 1; i < 31; i  ) { 
          a.push(i)
        }
        return a
      },
    }
  },

CodePudding user response:

You can access that via this.expired() instead of this.expired

new Vue({
  el: '#app',
  data () {
    return {
      labelEnable: "a",
      expired: () => [1, 3],
    }
  },
  mounted() {
    console.log(this.expired())
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p v-for="elem in expired()">{{ elem }}</p>
</div>

CodePudding user response:

You declare a function which calculates expired, but you don't call and execute it. Try this:

  expired: (() => {
    var a = []
    for (var i = 1; i < 31; i  ) { 
      a.push(i)
    }
    return a
  })(),

But for this particular example there is a more clear solution:

expired: new Array(30).fill().map((d, i) => i   1)
  • Related