javascript 如何在Vue 3中将 prop 传递给css类

8tntrjer  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(281)

我必须创建一个带有自定义消息和类的通用吐司组件。我成功地传递了消息props而没有问题,但是我仍然不能用引导类来做。
孩子:吐司面包

<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>

父主页版本:

<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>
qvtsj1bj

qvtsj1bj1#

class是一个fallthrough attribute,它是直接传递的,不需要声明为prop,所以为了避免这种行为,应该防止继承该属性:

<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>
b4qexyjb

b4qexyjb2#

当我传递类属性时,我在子组件的模板代码中发现了一个错误:

<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>

相关问题