实现效果:
写在前面:
在开发一个项目时,在多个页面都使用了切换就诊卡这个组件,为了避免重复写同一个组件,所以将这个组件抽离出来,形成一个独立的组件,增强代码的复用性,本文就来详细睡眠如何做,只需两步:封装子组件,使用子组件。
实现步骤:
封装子组件
1.首先将组件代码抽离出来,删掉多余的部分,只留下组件内容的代码,以及scss样式,在components文件夹下新建一个CardChange.vue
代码如下:
<template>
<div class="people_content">
<!-- 新版就诊卡 -->
<div class="card_first">
<span class="title">{{ cardList[selectedIndex].name }}<br />诊疗卡号:{{ cardList[selectedIndex].relation
}}</span>
<span class="add" @click="show = true">切换就诊卡</span>
</div>
<!-- 就诊卡弹窗 -->
<van-popup v-model="show" round position="bottom" :style="{ height: '40%' }">
<div class="patient_card">
<div :class="{ active_card: selectedIndex === index }" class="card" v-for="(item, index) in cardList"
:key="index" @click="clickCard(index)">
<span class="name">{{ item.name }}</span>
<span class="relation">{{ item.relation }}</span>
</div>
<div class="add" @click="goToAddPatient">
<span><van-icon name="add-o" />添加就诊人</span>
</div>
</div>
</van-popup>
</div>
</template>
2.在子组件中定义一个props,接受父组件传入的值,展现到页面中
export default {
// 接受父组件数据
props: {
cardList: {
type: Array,
required: true
}
},
}
在父组件中使用子组件:
方式一:使用props方式
第一步:导入子组件:
// 导入子组件
import CardChange from "../../../components/CardChange/CardChange";
第二步:将子组件CardChange注册为父组件components对象中的一个属性
export default {
// 将子组件CardChange注册为父组件components对象中的一个属性
components:{
CardChange
},
第三步:在父组件中使用子组件
<CardChange :cardList="cardList"/>
方式二:使用v-model语法糖:
步骤与方式一基本一样,在子组件中加入:
model: {
prop: 'cardList',
event: ''
},
即可在父组件中以v-model的方式使用
<CardChange v-model="cardList"/>