业务组件是Vant的一大特点,特别是针对移动端商城开发的业务,有许多组件可以直接运用到通用商城的开发中,代码也十分简单,大大加快了应用的开发速度。
在众多的业务组件中,Card 卡片、Coupon 优惠券选择器和SubmitBar 提交订单栏是三款常用的业务组件,接下来结合实例,分别演示它们使用的过程。
Card 组件
Card 组件用于展示商品的完整信息,包括商品图片、价格、标签和促销信息,还可以显示商品的多种标签,自定义商品的底部操作按钮,常用于购物车商品信息的展示和商品列表信息的显示,它的常用属性如下表11-9所示。
接下来通过一个完整的案例来演示使用Card组件实现的效果。
实例11-7 Card组件
1. 功能描述
创建一个页面,定义一条包含商品信息的数据,并使用van-card组件展示这条数据,同时,在底部分别添加自加和自减按钮,当点击按钮时,商品数量进行相应的增加或减少。
2. 实现代码
在项目的components 文件夹中,添加一个名为“Card”的.vue文件,该文件的保存路径是“components/ch11/buis/”,在文件中加入如清单11-7所示代码。
代码清单11-7 Card.vue代码
<template><h3>Card 组件</h3><div class="row"><van-card :num="curGoods.num" :tag="curGoods.tag" :price="curGoods.price" :desc="curGoods.desc":title="curGoods.title" :thumb="curGoods.thumb" :origin-price="curGoods.originPrice"><template #tags><van-tag plain type="primary">{{ curGoods.tags[0] }}</van-tag><van-tag plain type="primary">{{ curGoods.tags[1] }}</van-tag></template><template #footer><van-button size="mini" @click="add">+</van-button><van-button size="mini" @click="reduce">-</van-button></template></van-card></div>
</template>
<script>
import goods from "../../../assets/goods.png"
export default {data() {return {curGoods: {num: 2, price: 9000,desc: "一台笔记本电脑",title: "thinkpad X1 系列",thumb: goods,originPrice: "11000",tag: "超薄小巧型",tags:["一代经典","超低价格"]}}},methods: {add() {this.curGoods.num++;},reduce() {if (this.curGoods.num > 1)this.curGoods.num--;}}
}
</script>
<style>
.row {margin: 10px 0;padding: 10px 0;border-bottom: solid 1px #eee;
}.van-image img {object-fit: contain !important;
}
</style>
3. 页面效果
保存代码后,页面在Chrome浏览器下执行的页面效果如图11-9所示。
4. 源码分析
Card 组件中提供了大量的slot插槽,可以很方便地自定义商品的其他标签和操作元素,如在本实例的商品信息底部增加自加和自减按钮,同时,在操作这类按钮时,通常关联商品的相关信息,如数量,当形成关联关系后,如果用户点击了自加按钮,那么商品数量会自动在原有基础上加1,同时,展示数量的信息也会自动同步变更。