[Vuejs]-How to make a condition to add/remove data param in Vue?

0👍

You could compose your attributes as an object in a computed property:

computed: {
  attributes() {
    let attributes = {};
    if (this.someData) {
      attributes['data-some'] = this.someData;
    }
    if (this.someOtherData) {
      attributes['data-someother'] = this.someOtherData;
    }
    return attributes;
  }
}

And then bind those attributes to the div by passing the object to the v-bind directive:

<div v-bind="attributes"></div>

This way, if the data for a data-param doesn’t exist, that data-param attribute won’t be added to the attributes object, and won’t be bound to the div.

Leave a comment