stwilson's avatar

v-if: how to test if object is empty?

Trying to do figure out how to check my data object empty or not. No matter what I try, I get "error when evaluating expression".

Here's what I'm trying to figure out. my-object is fetched by ajax, and I don't want to display certain elements until the object is not empty.

<span v-if=" my-object.areyouemptyornot ">See me or not</span>
0 likes
7 replies
kfirba's avatar
kfirba
Best Answer
Level 50

@stwilson hey.

First, you can't use a dash (-) in a variable name.

For the answer itself, I would initiate the object value to null and check against it:

<span v-if="myObject">some text</span>

The data object should look like:

data() {
    return {
        myObject: null
    }
}

When you populate the myObject property, it won't be null anymore , hence the span will be inserted into the DOM.

2 likes
stwilson's avatar

@kfirba It was the setting to null I couldn't think of. Exactly what I needed. Thank you.

stwilson's avatar

@kfirba This works initially, however, when the ajax request is sent again and returns empty, myObject becomes an empty array.

I can't seem to cast it back myObject back to null. I'm back to finding a way to return myObject empty, true or false.

erikverbeek's avatar

You could check the returned object length in the handling of your ajax request. Something like:

if(response.myObject.length == 0) this.myObject = null;
else this.myObject = response.myObject;
stwilson's avatar

Thank you. I ended up setting myObject = [], similar to the initial solution, then checking:

<span v-if="myObject[0]">some text</span>

That seems to get it done. Thanks again!

1 like
stwilson's avatar

@erikverbeek Your answer also works for me like this:

this.$http.get(`api/myObject/${this.id}`, function(myObject) {
    if(myObject.length == 0) this.myObject = null;
    else this.myObject = myObject;
}.bind(this));
alexteie's avatar

Ok so i can use this?

in the main blade file

<script>
	var app = new Vue({
		el: '#app',
		mixins: [mixin],
		data: {
			showContactAddress: {!!$Contact->use_address!!},
			showOrganizationAddress: {!!$Contact->use_org_label!!},
			grouptagsSelected: {!!$Contact->grouptags->pluck('id')!!},
			earmarksSelected: {!!$Contact->earmarks->pluck('id')!!}
		},
		methods: {

		}
	});
</script>

en mine extend file this?

<script>
var mixin = {
  data: {
	f_active: {!!$Contact->f_Active!!}
    }
  }
}
</script>

Please or to participate in this conversation.