skip to Main Content

I must create a generic toast component with a custom message and class. I managed to pass a message props without problems but I still can’t do it with the bootstrap class.

child: Toast.vue

<script setup>
const props = defineProps({
  message:{
    type:String,
    default:'Mon message'
  },
  class:{
    type:String,
    default:'text-bg-info'
  }
})
</script>

<template>
  <div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div ref="toast1" id='showToast' class="toast" :class={{props.class}} role="alert">
      <div class="toast-body">
        <span>{{ props.message }}</span>
      </div>
    </div>
  </div>
</template>

Parent Home.vue:

<script setup>
import Form from '../components/Form.vue'
import Toast from '../components/Toast.vue'
</script>

<template>
  <main class="mt-5">
    <Form />
    <Toast
    message="Created"
    class="text-bg-success"
    ></Toast>
  </main>
</template>
```

2

Answers


  1. Chosen as BEST ANSWER

    I found an error in my template code in child component when I pass class props:

    
    <template>
      <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <div ref="toast1" id='showToast' class="toast" :class="props.class" role="alert">
          <div class="toast-body">
            <span>{{ props.message }}</span>
          </div>
        </div>
      </div>
    </template>
    ```
    

  2. class is a fallthrough attribute and it’s passed directly without the need to declare it as prop, so to avoid the behavior you should prevent inheriting that attribute :

    <script>
    export default {
      inheritAttrs: false
    }
    </script>
    
    <script setup>
    const props = defineProps({
      message:{
        type:String,
        default:'Mon message'
      },
    })
    </script>
    
    <template>
      <div class="toast-container position-fixed bottom-0 end-0 p-3">
        <div ref="toast1" id='showToast' class="toast" :class="$attrs.class" role="alert">
          <div class="toast-body">
            <span>{{ message }}</span>
          </div>
        </div>
      </div>
    </template>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search