Vue3中如何向CSS类传递Props?自定义Toast组件类传递问题
问题原因与修复方案
1. 避免使用保留字作为Prop名称
Vue 中 class 是原生属性的保留字,将其用作 Prop 名称会导致语法冲突,无法正确传递自定义类名。需将 Prop 重命名为如 toastClass 这类非保留名称。
2. 修正:class绑定语法
模板中 :class={{props.class}} 的写法错误,Vue 动态类绑定不需要嵌套双大括号,直接引用 Prop 即可。
修正后的子组件 Toast.vue
<script setup> const props = defineProps({ message: { type: String, default: 'Mon message' }, // 重命名Prop以避免冲突 toastClass: { 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="toastClass" role="alert"> <div class="toast-body"> <span>{{ message }}</span> </div> </div> </div> </template>
修正后的父组件 Home.vue
<script setup> import Form from '../components/Form.vue' import Toast from '../components/Toast.vue' </script> <template> <main class="mt-5"> <Form /> <!-- 使用重命名后的Prop传递类名 --> <Toast message="Created" toastClass="text-bg-success" ></Toast> </main> </template>
额外提示
若要让 Toast 正常显示,需通过 Bootstrap JavaScript 初始化实例,可在 Toast.vue 中添加生命周期钩子:
<script setup> import { onMounted, ref } from 'vue' const props = defineProps({ // ... 保持原有Prop定义 }) const toast1 = ref(null) onMounted(() => { if (toast1.value) { const toast = new bootstrap.Toast(toast1.value) toast.show() } }) </script>
内容的提问来源于stack exchange,提问作者Deotyma
相关产品推荐
相关产品推荐

