Home > Software engineering >  Can I use props in computed property to bind a css class?
Can I use props in computed property to bind a css class?

Time:02-16

Is it possible to use the props inside a computed property, in some other way?

When I do this, it add the class 'foo' (name of the props), instead the wanted 'fa-too' (or other value, if props were set).

Both works, if I only bind one of them, directly in the markup.

props: {
  foo: {
    type: String,
    default: 'fa-foo'
  }
},

computed: {
  classObject: function () {
    return {
      foo: true,
      'text-danger': true
    }
  }
}

CodePudding user response:

The object syntax of class bindings applies the key as the class name when the value is truthy. Since the computed prop return value includes { foo: true }, the "foo" class is applied.

To set the value of the foo prop as the class name, you can use this.foo as the key with brackets:

computed: {
  classObject: function () {
    return {
      [this.foo]: true,
      'text-danger': true
    }
  }
}

Class bindings also allow an array of strings and objects, so the computed prop could also be written as:

computed: {
  classObject: function () {
    return [
      this.foo,
      {
        'text-danger': true
      }
    ]
  }
}

...or just an array of strings:

computed: {
  classObject: function () {
    return [
      this.foo,
      'text-danger',
    ]
  }
}

demo

CodePudding user response:

you have to use this.foo to access the prop, because of the different scopes

  • Related