vue.js proper way to determine empty object

You can just use length of inventory in v-if, like following:

<div id="element">
  <div v-if="!inventory.length">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}
      <button v-on:click="remove(index)">remove</button>
  </div>
</div>

Given that inventory variable is a hash and not an array, you can use any of the following to find it is empty and use that in v-if:

ECMA 5+:

Object.keys(inventory).length === 0

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

As you are already using jquery, you can also do:

jQuery.isEmptyObject({}); // true

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>

<div id="element">

  <div v-if="isEmpty">No item in inventory</div>
  <div v-for="(index, item) in inventory">
      {{item.key}}<button @click="remove(index)">remove</button>
  </div>
</div>

<script type="text/javascript">
"use strict";
var vm;
$(function() {
    vm = new Vue({
        el: '#element',
        data: {
            inventory: {"id1" : {"key" : "val1"}, "id2" : {"key" : "val2"}},
            empty: false
        },
        methods: {
            remove: function(index) {
                Vue.delete(this.inventory, index);
                
            }
        },
        computed: {
           isEmpty: function () {
              return jQuery.isEmptyObject(this.inventory)
           }
       }
    });
});
</script>

Leave a Comment