Vue data (this.numberOfBars) out of scope in a nested loop

Viewed 51

I'm very new to vue and can't figure this issue out. Spent hours on google without any luck. As soon as I add the parent look (j in 3) this.numberOfBars becomes out of scope. Unfortunately, in this one off quick project, I simply don't know what I don't know. Can anyone help as to what I'm doing wrong?

const app = new Vue({
  el: '#app',
  methods: {
    bars() {
      const bars = []
      for (let i = 0; i < this.numberOfBars; i++) {
        bars.push(Math.sqrt(this.numberOfBars * this.numberOfBars - i * i))
      }
      return bars
    },
  },
  data() {
    return {
      scale: 2,
      numberOfBars: 30,
    }
  },
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div style="clear: left" v-for="j in 3">
    <div v-for="(y, i) in bars()" :key="i" :style="{ width: scale * j, height: (numberOfBars * j) * scale, float: 'left', borderTop: (y * scale) + 'px solid blue' }">
    </div>
    PI = {{ bars().reduce((a, b) => a+(4*b)/Math.pow(this.numberOfBars * j, 2), 0) }}

  </div>
</div>

1 Answers

In your template, you don't need this:

const app = new Vue({
  el: '#app',
  methods: {
    bars() {
      const bars = []
      for (let i = 0; i < this.numberOfBars; i++) {
        bars.push(Math.sqrt(this.numberOfBars * this.numberOfBars - i * i))
      }
      return bars
    },
  },
  data() {
    return {
      scale: 2,
      numberOfBars: 30,
    }
  },
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <div style="clear: left" v-for="j in 3">
    <div v-for="(y, i) in bars()" :key="i" :style="{ width: scale * j + 'px', height: (numberOfBars * j) * scale + 'px', float: 'left', borderTop: (y * scale) + 'px solid blue' }">
    </div>
    PI = {{ bars().reduce((a, b) => a+(4*b)/Math.pow(numberOfBars * j, 2), 0) }}
    <!-- remove this before numberOfBars -->

  </div>
</div>

Related