效果预览

vue3【实战-组件封装】图文卡片_vue3

技术要点

  • 图片宽高比固定为 16:9,展示方式为 object-fit: cover
  • 通过 v-bind 实现父组件向子组件的批量传参
  • 单行文本超长显示省略号
white-space: nowrap;
overflow: hidden; 
text-overflow: ellipsis;
  • title 属性实现鼠标悬浮显示文本完整内容

范例代码

src/components/Card.vue

<script setup lang="ts">
defineProps({
  image: String,
  imageInfo: String,
  title: String,
  subTitle: String
})
</script>

<template>
  <!-- overflow-hidden 确保图片不会溢出容器-->
  <div
    class="m-2 border border-gray-300 inline-block rounded-1.5 overflow-hidden cursor-pointer w-48"
  >
    <!-- 图片展示比例为 16:9 ,比例不符合的图片会自适应裁剪-->
    <img :src="image" :alt="imageInfo" class="w-48 h-27" style="object-fit: cover" />

    <div class="p-2">
      <div
        class="text-sm text-dark-300 text-bold mb-1"
        style="text-overflow: ellipsis; overflow: hidden; white-space: nowrap"
        :title="title"
      >
        {{ title }}
      </div>
      <div class="text-xs text-dark-100 font-300">{{ subTitle }}</div>
    </div>
  </div>
</template>

使用

<script setup lang="ts">
let cardInfo = {
  image:
    'https://img0.baidu.com/it/u=998088135,496941855&fm=253&fmt=auto&app=138&f=PNG?w=600&h=300',
  imageInfo: '前端课程封面',
  title: '2024年-零基础学前端系列课程',
  subTitle: '一学就会,前端速成'
}
</script>

<template>
  <Card v-bind="cardInfo" />
</template>