0

I'm using vue-cli and I'm trying to figure out how to update counter in my template:

<div v-for="(item, index) in outerArray" :key="item.id" v-bind:id="item.name">
   <div>  <p> {{ item.name }}</p> </div>
<div>Count:{{count}}</div>

I would like the counter to update for each user based off of how many alerts are in warning array:

outerArray:[
             { name: 'Ray',
               count: null,
               warning: [{time: '2:00', alert: 'G: 150',},
                         {time: '7:00', alert: 'RR: 38',}]
              },
             { name: 'Mike',
               count: null,
               warning:[{time: '9:00',alert: 'G: 40',}]
             },
    
            ]

So the output should look like:

Ray           Mike
Count:2       Count:1

Any help would be appreciated, thanks!

Update

I used:

this.outerArray[index].warning.length

to display how many alerts were in warnings.

1 Answer 1

2

If this value only changes from item to item, then:

new Vue({
  el: "#app",
  data: {
    outerArray: [{
        name: 'Ray',
        count: null,
        warning: [{
            time: '2:00',
            alert: 'G: 150',
          },
          {
            time: '7:00',
            alert: 'RR: 38',
          }
        ]
      },
      {
        name: 'Mike',
        count: null,
        warning: [{
          time: '9:00',
          alert: 'G: 40',
        }]
      },
    ]
  },
  methods: {
    countWarnings(item) {
      return item.warning.length
    }
  },
  mounted() {
    this.outerArray.forEach(e => {
      e.count = e.warning.length
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(item, index) in outerArray" :key="item.id" v-bind:id="item.name">
    <div>
      <p>{{ item.name }}</p>
    </div>
    <div>Count (from item.warning): {{ item.warning.length }}</div>
    <div>Count (with item.count set at mounted): {{ item.count }}</div>
    <div>Count (with a count method): {{ countWarnings(item) }}</div><br />
    If you're not sure, what a variable holds, you can either use the Vue extension (in Chrome), the console or the screen:<br />
    - The item is: {{ item }}<br />
    - The item.warning is: {{ item.warning }}<br />
    - The item.warning.length is: {{ item.warning.length }}
    <br />
    <hr />
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

@YJay I’m happy that I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.