firatinlkc
firatinlkc

Reputation: 30

How can I do this with Vue js?

data: [
  {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
  {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
]

I have data similar to this and I need to get the number of online users here and print it on the screen vue js how can I do it? I found it a long way but it didn't work

Upvotes: 0

Views: 64

Answers (1)

tony19
tony19

Reputation: 138656

You could use Array.prototype.filter() to find all the array entries that have status: 'online', then return the length of that array:

const onlineUsers = data.filter(x => x.status === 'online')
const onlineCount = onlineUsers.length

To show that count in a Vue template, you could compute the result above and use string interpolation syntax (prop name between {{ and }}):

new Vue({
  el: '#app',
  data() {
    return {
      data: [
        {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'online'},
        {name: 'xxxxx', surname: 'yyyyy', status: 'offline'},
      ]
    };
  },
  computed: {
    onlineCount() {
      return this.data.filter(x => x.status === 'online').length;
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js"></script>
<div id="app">
  <div>{{onlineCount}} users are online</div>
</div>

Upvotes: 1

Related Questions