'Passing prop and using it as a part of a className

I have a parent component <Spinner /> which passes the spinner size size="sm" to the child component. The parent component looks like this:

<template>
      <div v-if="isPending">
          <Spinner size="sm" />
          <span> Loading data...</span>
      </div>
</template>

The child component looks like this:

<template>
      <span class="spinner-border spinner-border-{{ size }}"></span>
</template>
    
<script>
  export default {
       props: ['size']
  }
</script>

The child component throws an error because class="spinner-border spinner-border-{{ size }}" is not the proper way to add sm to spinner-border-. I'm looking for an elegant way to add only the size suffix sm (not adding the whole spinner-border-sm class)



Solution 1:[1]

You need to bind your class with :class or v-bind:class :

const app = Vue.createApp({
  data() {
    return {
      isPending: true,
    };
  },
})
app.component('Spinner', {
  template: `
    <div class="">
      <span :class="'spinner-border spinner-border-'+size">{{ size }}</span>
    </div>
  `,
  props: ['size'],
})
app.mount('#demo')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-if="isPending">
    <spinner size="sm"></spinner>
    <span> Loading data...</span>
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1