当前位置:   article > 正文

小程序学习3 goods-card

小程序学习3 goods-card

pages/home/home

        home.wxml

  1. <goods-list
  2. wr-class="goods-list-container"
  3. goodsList="{{goodsList}}"
  4. bind:click="goodListClickHandle"
  5. bind:addcart="goodListAddCartHandle"
  6. />

<goods-list>是一个自定义组件,它具有以下属性和事件:

属性:

  • wr-class:用于设置组件容器的样式类名。
  • goodsList:用于传递商品列表数据给组件。

事件:

  • click:当用户点击商品列表中的某个商品时触发该事件,可以通过绑定该事件来执行相应的处理函数。
  • addcart:当用户点击商品列表中的添加购物车按钮时触发该事件,可以通过绑定该事件来执行相应的处理函数。

可以根据需要设置wr-class属性来自定义组件的样式,同时通过goodsList属性传递商品列表数据给组件。另外,你还可以绑定click事件和addcart事件来处理用户的点击操作。

        home.json

  1. "usingComponents": {
  2. "goods-list": "/components/goods-list/index",
  3. }

        home.js

  1. import { fetchHome } from '../../services/home/home';
  2. import { fetchGoodsList } from '../../services/good/fetchGoods';
  3. import Toast from 'tdesign-miniprogram/toast/index';
  4. Page({
  5. data: {
  6. imgSrcs: [],
  7. tabList: [],
  8. goodsList: [],
  9. goodsListLoadStatus: 0,
  10. pageLoading: false,
  11. current: 1,
  12. autoplay: true,
  13. duration: '500',
  14. interval: 5000,
  15. navigation: { type: 'dots' },
  16. swiperImageProps: { mode: 'scaleToFill' },
  17. },
  18. goodListPagination: {
  19. index: 0,
  20. num: 10,
  21. },
  22. privateData: {
  23. tabIndex: 0,
  24. },
  25. onShow() {
  26. this.getTabBar().init();
  27. },
  28. onLoad() {
  29. this.init();
  30. },
  31. onReachBottom() {
  32. if (this.data.goodsListLoadStatus === 0) {
  33. this.loadGoodsList();
  34. }
  35. },
  36. onPullDownRefresh() {
  37. this.init();
  38. },
  39. init() {
  40. this.loadHomePage();
  41. },
  42. loadHomePage() {
  43. wx.stopPullDownRefresh();
  44. this.setData({
  45. pageLoading: true,
  46. });
  47. fetchHome().then(({ swiper, tabList }) => {
  48. this.setData({
  49. tabList,
  50. imgSrcs: swiper,
  51. pageLoading: false,
  52. });
  53. this.loadGoodsList(true);
  54. });
  55. },
  56. tabChangeHandle(e) {
  57. this.privateData.tabIndex = e.detail;
  58. this.loadGoodsList(true);
  59. },
  60. onReTry() {
  61. this.loadGoodsList();
  62. },
  63. async loadGoodsList(fresh = false) {
  64. if (fresh) {
  65. wx.pageScrollTo({
  66. scrollTop: 0,
  67. });
  68. }
  69. this.setData({ goodsListLoadStatus: 1 });
  70. const pageSize = this.goodListPagination.num;
  71. let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
  72. if (fresh) {
  73. pageIndex = 0;
  74. }
  75. try {
  76. const nextList = await fetchGoodsList(pageIndex, pageSize);
  77. this.setData({
  78. goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
  79. goodsListLoadStatus: 0,
  80. });
  81. this.goodListPagination.index = pageIndex;
  82. this.goodListPagination.num = pageSize;
  83. } catch (err) {
  84. this.setData({ goodsListLoadStatus: 3 });
  85. }
  86. },
  87. goodListClickHandle(e) {
  88. const { index } = e.detail;
  89. const { spuId } = this.data.goodsList[index];
  90. wx.navigateTo({
  91. url: `/pages/goods/details/index?spuId=${spuId}`,
  92. });
  93. },
  94. goodListAddCartHandle() {
  95. Toast({
  96. context: this,
  97. selector: '#t-toast',
  98. message: '点击加入购物车',
  99. });
  100. },
  101. navToSearchPage() {
  102. wx.navigateTo({ url: '/pages/goods/search/index' });
  103. },
  104. navToActivityDetail({ detail }) {
  105. const { index: promotionID = 0 } = detail || {};
  106. wx.navigateTo({
  107. url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
  108. });
  109. },
  110. });
 解析:async loadGoodsList(fresh = false) {

说白了,这段儿代码就是鼠标滚轮往下拉,商品列表就刷刷刷的往外刷

这段代码是一个异步函数loadGoodsList,它接受一个参数fresh,默认为false。函数的作用是加载商品列表。

首先,如果freshtrue,则调用wx.pageScrollTo函数将页面滚动到顶部

然后,通过调用setData方法将goodsListLoadStatus设置为1,表示正在加载商品列表。

接下来,根据当前的页码和每页的数量计算出要请求的页码。如果freshtrue,则将页码设置为0。

然后,使用fetchGoodsList函数异步获取商品列表。获取到列表后,通过调用setData方法将goodsList更新为新的列表。如果是刷新操作,则直接使用新的列表;如果是加载更多操作,则将新的列表与原有列表合并。同时,将goodsListLoadStatus设置为0,表示加载完成。

最后,更新分页信息,将页码和每页数量保存到goodListPagination对象中。

如果在获取商品列表过程中发生错误,则通过调用setData方法将goodsListLoadStatus设置为3,表示加载失败。

  goodListAddCartHandle() {  }
  1. goodListAddCartHandle() {
  2. Toast({
  3. context: this,
  4. selector: '#t-toast',
  5. message: '点击加入购物车',
  6. });
  7. },

TDesign    Toast 轻提示

用于轻量级反馈或提示,不会打断用户操作。

goodListAddCartHandle()是一个函数,用于处理点击加入购物车的操作。在函数内部,它会调用Toast组件来显示一个提示消息,提示用户已成功将商品加入购物车。

在函数中,Toast组件的参数包括:

  • context:表示上下文,即函数所在的环境或组件。
  • selector:表示选择器,用于指定要显示提示消息的位置。
  • message:表示要显示的提示消息内容,这里是"点击加入购物车"。

这样,当用户点击加入购物车时,函数会调用Toast组件来显示提示消息。

components/goods-list

        index.wxml

  1. <view class="goods-list-wrap wr-class" id="{{independentID}}">
  2. <block wx:for="{{goodsList}}" wx:for-item="item" wx:key="index">
  3. <goods-card
  4. id="{{independentID}}-gd-{{index}}"
  5. data="{{item}}"
  6. currency="{{item.currency || '¥'}}"
  7. thresholds="{{thresholds}}"
  8. class="goods-card-inside"
  9. data-index="{{index}}"
  10. bind:thumb="onClickGoodsThumb"
  11. bind:click="onClickGoods"
  12. bind:add-cart="onAddCart"
  13. />
  14. </block>
  15. </view>

        index.json

  1. {
  2. "component": true,
  3. "usingComponents": {
  4. "goods-card": "/components/goods-card/index"
  5. }
  6. }

components/goods-card

        index.wxml

  1. <view
  2. id="{{independentID}}"
  3. class="goods-card"
  4. bind:tap="clickHandle"
  5. data-goods="{{ goods }}"
  6. >
  7. <view class="goods-card__main">
  8. <view class="goods-card__thumb" bind:tap="clickThumbHandle">
  9. <t-image
  10. wx:if="{{ !!goods.thumb }}"
  11. t-class="goods-card__img"
  12. src="{{ goods.thumb }}"
  13. mode="aspectFill"
  14. lazy-load
  15. />
  16. </view>
  17. <view class="goods-card__body">
  18. <view class="goods-card__upper">
  19. <view wx:if="{{ goods.title }}" class="goods-card__title">
  20. {{ goods.title }}
  21. </view>
  22. <view wx:if="{{ goods.tags && !!goods.tags.length }}" class="goods-card__tags">
  23. <view
  24. wx:for="{{ goods.tags }}"
  25. wx:key="index"
  26. wx:for-item="tag"
  27. class="goods-card__tag"
  28. data-index="{{index}}"
  29. >
  30. {{tag}}
  31. </view>
  32. </view>
  33. </view>
  34. <view class="goods-card__down">
  35. <price
  36. wx:if="{{ goods.price }}"
  37. wr-class="spec-for-price"
  38. symbol-class="spec-for-symbol"
  39. symbol="{{currency}}"
  40. price="{{goods.price}}"
  41. />
  42. <price
  43. wx:if="{{ goods.originPrice && isValidityLinePrice }}"
  44. wr-class="goods-card__origin-price"
  45. symbol="{{currency}}"
  46. price="{{goods.originPrice}}"
  47. type="delthrough"
  48. />
  49. <t-icon
  50. class="goods-card__add-cart"
  51. prefix="wr"
  52. name="cartAdd"
  53. id="{{independentID}}-cart"
  54. data-id="{{independentID}}"
  55. catchtap="addCartHandle"
  56. size="48rpx"
  57. color="#FA550F"
  58. />
  59. </view>
  60. </view>
  61. </view>
  62. </view>
  <view class="goods-card__main">

TDesign  mode为   裁切

lazy-load

懒加载(Lazy Load)是一种延迟加载的策略,它在编程中常用于优化系统性能和资源利用。懒加载的核心思想是将对象的创建或数据的加载推迟到真正需要的时候再进行,而不是在初始化阶段就立即进行。

懒加载的优点是可以减少系统启动时间和内存占用,特别适用于大型系统或者需要加载大量资源的场景。通过懒加载,可以避免不必要的资源浪费,提高系统的响应速度和效率。

在软件开发中,懒加载可以应用于多个方面,比如:

  1. 对象的懒加载:当一个对象在程序中被创建时,并不立即初始化其成员变量或关联对象,而是在真正需要使用时才进行初始化。这样可以避免不必要的对象创建和资源消耗。

  2. 数据库查询的懒加载:在使用ORM(对象关系映射)框架进行数据库操作时,可以延迟加载关联对象的数据。只有当访问关联对象时才会触发实际的数据库查询操作,从而减少数据库访问次数和提高查询效率。

  3. 图片或文件的懒加载:在网页或移动应用中,可以延迟加载图片或文件资源。当用户滚动到可见区域时,再进行实际的资源加载,避免一次性加载大量资源导致页面卡顿或流量浪费。

       index.json

  1. {
  2. "component": true,
  3. "usingComponents": {
  4. "price": "/components/price/index",
  5. "t-icon": "tdesign-miniprogram/icon/icon",
  6. "t-image": "/components/webp-image/index"
  7. }
  8. }
        index.js
  1. Component({
  2. options: {
  3. addGlobalClass: true,
  4. },
  5. properties: {
  6. id: {
  7. type: String,
  8. value: '',
  9. observer(id) {
  10. this.genIndependentID(id);
  11. if (this.properties.thresholds?.length) {
  12. this.createIntersectionObserverHandle();
  13. }
  14. },
  15. },
  16. data: {
  17. type: Object,
  18. observer(data) {
  19. if (!data) {
  20. return;
  21. }
  22. let isValidityLinePrice = true;
  23. if (data.originPrice && data.price && data.originPrice < data.price) {
  24. isValidityLinePrice = false;
  25. }
  26. this.setData({ goods: data, isValidityLinePrice });
  27. },
  28. },
  29. currency: {
  30. type: String,
  31. value: '¥',
  32. },
  33. thresholds: {
  34. type: Array,
  35. value: [],
  36. observer(thresholds) {
  37. if (thresholds && thresholds.length) {
  38. this.createIntersectionObserverHandle();
  39. } else {
  40. this.clearIntersectionObserverHandle();
  41. }
  42. },
  43. },
  44. },
  45. data: {
  46. independentID: '',
  47. goods: { id: '' },
  48. isValidityLinePrice: false,
  49. },
  50. lifetimes: {
  51. ready() {
  52. this.init();
  53. },
  54. detached() {
  55. this.clear();
  56. },
  57. },
  58. pageLifeTimes: {},
  59. methods: {
  60. clickHandle() {
  61. this.triggerEvent('click', { goods: this.data.goods });
  62. },
  63. clickThumbHandle() {
  64. this.triggerEvent('thumb', { goods: this.data.goods });
  65. },
  66. addCartHandle(e) {
  67. const { id } = e.currentTarget;
  68. const { id: cardID } = e.currentTarget.dataset;
  69. this.triggerEvent('add-cart', {
  70. ...e.detail,
  71. id,
  72. cardID,
  73. goods: this.data.goods,
  74. });
  75. },
  76. genIndependentID(id) {
  77. let independentID;
  78. if (id) {
  79. independentID = id;
  80. } else {
  81. independentID = `goods-card-${~~(Math.random() * 10 ** 8)}`;
  82. }
  83. this.setData({ independentID });
  84. },
  85. init() {
  86. const { thresholds, id } = this.properties;
  87. this.genIndependentID(id);
  88. if (thresholds && thresholds.length) {
  89. this.createIntersectionObserverHandle();
  90. }
  91. },
  92. clear() {
  93. this.clearIntersectionObserverHandle();
  94. },
  95. intersectionObserverContext: null,
  96. createIntersectionObserverHandle() {
  97. if (this.intersectionObserverContext || !this.data.independentID) {
  98. return;
  99. }
  100. this.intersectionObserverContext = this.createIntersectionObserver({
  101. thresholds: this.properties.thresholds,
  102. }).relativeToViewport();
  103. this.intersectionObserverContext.observe(
  104. `#${this.data.independentID}`,
  105. (res) => {
  106. this.intersectionObserverCB(res);
  107. },
  108. );
  109. },
  110. intersectionObserverCB() {
  111. this.triggerEvent('ob', {
  112. goods: this.data.goods,
  113. context: this.intersectionObserverContext,
  114. });
  115. },
  116. clearIntersectionObserverHandle() {
  117. if (this.intersectionObserverContext) {
  118. try {
  119. this.intersectionObserverContext.disconnect();
  120. } catch (e) {}
  121. this.intersectionObserverContext = null;
  122. }
  123. },
  124. },
  125. });

properties     
        data
  1. data: {
  2. type: Object,
  3. observer(data) {
  4. if (!data) {
  5. return;
  6. }
  7. let isValidityLinePrice = true;
  8. if (data.originPrice && data.price && data.originPrice < data.price) {
  9. isValidityLinePrice = false;
  10. }
  11. this.setData({ goods: data, isValidityLinePrice });
  12. },
  13. },

这段代码是一个小程序中的一个数据观察器(observer用于监听一个名为"data"的对象类型数据的变化。当"data"对象发生变化时,触发observer函数进行处理。

在observer函数中,首先判断"data"是否存在,如果不存在则直接返回。接着,通过比较"data"对象中的"originPrice"和"price"属性的值,判断是否满足某个条件(即"originPrice"小于"price"),并将结果保存在名为"isValidityLinePrice"的变量中。

最后,通过调用小程序的setData方法,将"data"对象以及"isValidityLinePrice"变量的值更新到小程序的数据中。

        thresholds: {

thresholds是一个属性,它是一个数组类型,初始值为空数组。在该属性的观察器(observer)中,当thresholds发生变化时,会执行相应的操作。

在这段代码中,当thresholds存在且长度大于0时,会调用createIntersectionObserverHandle()方法;否则,会调用clearIntersectionObserverHandle()方法。

createIntersectionObserverHandle是一个用于创建IntersectionObserver实例的函数。IntersectionObserver一个用于观察目标元素与其祖先元素或视窗交叉状态的API。通过使用IntersectionObserver,我们可以监听目标元素进入或离开视窗,或者与其祖先元素交叉的情况。

createIntersectionObserverHandle函数的作用是创建一个IntersectionObserver实例,并返回一个用于控制观察行为的句柄。通过这个句柄,我们可以对观察行为进行控制,例如开始观察、停止观察、设置观察回调等。

                createIntersectionObserverHandle

IntersectionObserver | 微信开放文档

使用createIntersectionObserverHandle函数的一般步骤如下:

  1. 调用createIntersectionObserverHandle函数创建一个IntersectionObserver实例的句柄。
  2. 通过句柄调用observe方法,指定要观察的目标元素。
  3. 设置观察回调函数,当目标元素与其祖先元素或视窗交叉状态发生变化时,会触发该回调函数。
  4. 可选地,通过句柄调用unobserve方法停止对目标元素的观察。
                IntersectionObserver

IntersectionObserver是一个用于监测元素是否进入或离开视口的API。它可以帮助我们实现懒加载、无限滚动、可见性检测等功能。

IntersectionObserver的基本原理是通过创建一个观察器(IntersectionObserver对象),然后指定要观察的目标元素和一些配置选项。当目标元素进入或离开视口时,观察器会触发回调函数,我们可以在回调函数中执行相应的操作。

以下是IntersectionObserver的一些常用配置选项:

  1. root:指定根元素,即观察器所在的容器,默认为浏览器视口。
  2. rootMargin:指定根元素的边界,可以用来扩大或缩小触发回调的范围。
  3. threshold:指定目标元素可见性的阈值,可以是一个或多个0到1之间的值。

使用IntersectionObserver的基本步骤如下:

  1. 创建一个IntersectionObserver对象,并传入一个回调函数。
  2. 使用observe()方法指定要观察的目标元素。
  3. 在回调函数中处理目标元素进入或离开视口的情况。
methods:{   
    clickHandle() {
  1. clickHandle() {
  2. this.triggerEvent('click', { goods: this.data.goods });
  3. },

clickHandle()是一个函数,它的作用是触发一个名为’click’的事件,并传递一个包含商品信息的对象{ goods: this.data.goods }作为参数。这个函数通常用于处理点击事件,并将商品信息传递给其他组件或模块进行处理。

Class: EventManager | 微信开放文档   

微信小程序 组件传值(二) triggerEvent 子传父_triggerevent传多个参-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/241720
推荐阅读
相关标签
  

闽ICP备14008679号