思路分析
- 图中标出的四个部分都是可能会发生变化的,需要我们定义为可配置
- 主标题和副标题由于是纯文本,我们定义成props即可
- 右侧内容和主体内容由于可能会传入较为复杂的自定义模板,我们定义成slot利用插槽渲染
核心代码
(1)组件编写
Home/components/home-panel.vue
<script lang="ts" setup name="HomePanel"></script> <template> <div class="home-panel"> <div class="container"> <div class="head"> <h3>新鲜好物<small>新鲜出炉 品质靠谱</small></h3> <XtxMore to="/"></XtxMore> </div> 面板的内容 </div> </div> </template> <style scoped lang="less"> .home-panel { background-color: #fff; .head { padding: 40px 0; display: flex; align-items: flex-end; h3 { flex: 1; font-size: 32px; font-weight: normal; margin-left: 6px; height: 35px; line-height: 35px; small { font-size: 16px; color: #999; margin-left: 20px; } } } } </style>
(2)props处理src/views/home/components/home-panel.vue
标题和子标题应该有父组件传递进来,不能写死
<script lang="ts" setup name="HomePanel"> defineProps({ title: { type: String, required: true, }, subTitle: { type: String, required: true, }, }) </script>
(3)父组件传入title和subTitle
<script lang="ts"> import HomePanel from './components/home-panel.vue' </script> <!-- 新鲜好物 --> <HomePanel title="新鲜好物" subTitle="新鲜出炉 品质靠谱"></HomePanel>
(4)插槽处理,右侧的查看全部和面板具体的内容不应该写死src/views/home/components/home-panel.vue
<template> <div class="home-panel"> <div class="container"> <div class="head"> <h3> {{ title }}<small>{{ subTitle }}</small> </h3> + <!-- 具名插槽 --> + <slot name="right"></slot> </div> + <!-- 默认的内容插槽 --> + <slot></slot> </div> </div> </template>
(5)父组件修改
<!-- 新鲜好物 --> <HomePanel title="新鲜好物" subTitle="新鲜出炉 品质靠谱"> <template #right> <XtxMore to="/"></XtxMore> </template> <div>我是内容</div> </HomePanel> bTitle="新鲜出炉 品质靠谱"> <template #right> <XtxMore to="/"></XtxMore> </template> <div>我是内容</div> </HomePanel>