0

I am trying to create component where I will set 2 properties:

  1. string property for class name which should be set
  2. boolean property which resolve if this class will be added

my component looks like this:

<template>
      <span v-bind:class="{ classProp : booleanProp}"></span>
</template>
<script>
    export default {
      props: {
        classProp: {
          type: String,
          default: 'bg-alert'
        },
        booleanProp: {
          type: Boolean,
          default: false
      }
    }
</script>

When I use this component as you can see in following code span element has class classProp instead of bg-success

<my-component :booleanProp="true" :classProp="bg-success"></my-component>

required output:

<span class="bg-success"></span>

given output:

<span class="classProp"></span>

Thanks for answers.

1 Answer 1

2

Vue's object syntax for class will use classProp as the class name (same as would do it JavaScript for an object key), instead of computing it. For that you have to ES6's computed property name syntax:

<template>
      <span v-bind:class="{ [classProp] : booleanProp}"></span>
</template>

Also, when using v-bind (or the shorthand, :) dont forget to pass strings as you would in JavaScript, enclosed in quotes (or, you could omit the binding and instead pass it as a regular prop classProp="bg-success"):

<my-component :booleanProp="true" :classProp="'bg-success'"></my-component>

JSFiddle (don't mind the kebab-case props)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.