[Vue3] Home page main body - panel component packaging

HomeMain-Panel Assembly Package

The layout and structure of the two modules are very similar. We can extract a common panel component for reuse.

Goal: Encapsulate a common panel component

insert image description here

Idea analysis

  1. The four parts marked in the figure are all subject to change and need to be defined as configurable
  2. Since the main title and subtitle are plain text, we can define them as props
  3. Since the content on the right and the main content may be passed in a more complex custom template, we define it as a slot and use the slot to render

core code

(1) Component writing

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 processingsrc/views/home/components/home-panel.vue

The title and subtitle should be passed in by the parent component, not hard-coded

<script lang="ts" setup name="HomePanel">
defineProps({
    
    
  title: {
    
    
    type: String,
    required: true,
  },
  subTitle: {
    
    
    type: String,
    required: true,
  },
})
</script>

(3) The parent component passes in title and subTitle

<script lang="ts">
import HomePanel from './components/home-panel.vue'
</script>

<!-- 新鲜好物 -->
<HomePanel title="新鲜好物" subTitle="新鲜出炉 品质靠谱"></HomePanel>

(4) Slot processing, the view all on the right and the specific content of the panel should not be hard-codedsrc/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) Parent component modification

<!-- 新鲜好物 -->
<HomePanel title="新鲜好物" subTitle="新鲜出炉 品质靠谱">
  <template #right>
    <XtxMore to="/"></XtxMore>
  </template>
  <div>我是内容</div>
</HomePanel>
bTitle="新鲜出炉 品质靠谱">
  <template #right>
    <XtxMore to="/"></XtxMore>
  </template>
  <div>我是内容</div>
</HomePanel>

Guess you like

Origin blog.csdn.net/weixin_46862327/article/details/128999072