I know I could create a custom filter for this, but I find it a little annoying to check Object.keys().length
in templates to test if an object isn't empty when using v-show
or v-if
. Especially since data objects/ computed properties that return objects should always have an initial state of {}
and not null
.
The logic behind v-if and v-show is that they simply work based on the value's truthiness in JavaScript. An empty object is truthy, that's how the language works. Changing that would break cases where users expect an empty object to work. In my opinion explicitly checking wether it is empty is necessary and logical.
@yyx990803 I understand that, but can you think of any instance where an object passed into v-if
is ever falsey? I doubt anyone sets up their data to default to null, when it's going to be an object. It simply seems sensible to cast it, since it's likely only ever going to be {}
or a populated object. I know Angular does this and it made the checks inside the directive much cleaner.
You can create a mixin that expose a method to check for an object. You can also use a computed value
@syropian You should set it to null
if you want it to be falsy. And ng-if
and ng-show
uses the same logic that Vue does. What seems sensible to you seems counter-intuitive to me.
It's fine, agree to disagree I guess. ¯_(⊙︿⊙)_/¯
Hi @posva , can you give me an example for solve the problem ? Thanks a lot
@Nayir You should actually just use v-if="Object.keys(object).length
You can use a computed property to check that
Ideally, you should set the initial value as null
(falsy) instead of {}
(truthy)
A simple work around is create a computed property that output a bool value.
Let me explain you with an example:
YourComponentFile.vue (script section):
data() {
return {
myObject: {}
}
},
computed: {
hasMyObject: function() {
return Object.keys(this.myObject).length;
}
}
and in YourComponentFile.vue (template section):
<div v-if="hasMyObject"></div>
You can use lodash globally:
<div v-if="_.isEmpty(pet)">
@syropian You should set it to
null
if you want it to be falsy. Andng-if
andng-show
uses the same logic that Vue does. What seems sensible to you seems counter-intuitive to me.
But if you want this value to be reactive you can't set it to null
.
vue.esm.js:591 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value: null
Most helpful comment
The logic behind v-if and v-show is that they simply work based on the value's truthiness in JavaScript. An empty object is truthy, that's how the language works. Changing that would break cases where users expect an empty object to work. In my opinion explicitly checking wether it is empty is necessary and logical.