微信小程序组件封装-如何进行属性判断

版权声明:如要转发,请注明出处,小小喵的微博 https://blog.csdn.net/weixin_42881744/article/details/81705300

最近开发小程序,对小程序组件封装进行了一定的了解,现在分享下。
个人理解:底层组件封装最好原子化,不带业务逻辑,业务组件后期可以根据底层组件在进行封装开发。尽量做到一次开发,多处使用的效果,解放生产力,提高开发效率。

如果你没有任何小程序开发经验,可以结合官网的同时,参考下这个网站先学习一下https://www.w3cschool.cn/weixinapp/

下面以轮播图为例,讲下组件的封装:

一 、首先封装组件

创建swiper文件

这里写图片描述

index.json

{
  "component": true
}

index.js

下面详解

Component({
  /**
  * 组件的属性列表
  */
  properties: {
  },
  methods: {
  }
});

properties一般我们常定义属性,常用写法

properties: {
    // 面板指示点
    indicatorDots: {
      type: Boolean,
      value: true
    }
}

如果要对属性进行判断,之前我们用vue封装,常这么写

props: {
    type: {
         validator (value) {
             return oneOf(value, ['success', 'info', 'warning', 'error']);
         },
         default: 'info'
     }
}

不过小程序,不支持这种写法,会报错,我们可以这么写:
如果写错,会报错误提示:”Error:Not a value in an array”
这里写图片描述

index.wxml

这里的type控制轮播图的类型:是普通轮播图,还是一般我们在商品详情页中看到的那种轮播图
这里写图片描述

methods里写自定义方法,我是这么写的,根据类型进行不同的逻辑判断,如果你只是展示,可以不写这个方法:

methods: {
    myTabClicked(e){
      switch (this.properties.type){
        case 'default':
            let {item:item} = e.currentTarget.dataset;
            this.triggerEvent('mygourl',item); //回调方法
            break;
        case 'detailSwiper':
            this.setData({ bigPicFlag: !this.data.bigPicFlag });
            break;
        default:
            break;
      }
    }
 }

index.wxss

为了好截图,我放个压缩版的
这里写图片描述

二、页面中调用组件

这样组件就完成了,在页面中直接调用:
这里写图片描述

另外在json中定义:

{
  "navigationBarTitleText": "swiper",
  "usingComponents": {
    "p-swiper": "../../dist/swiper/index"
  }
}

三、效果为:

本来录屏了,可是超过5M了,传不上来,放几张图片意思下
这里写图片描述
这里写图片描述
这里写图片描述

希望对你有帮助,如果要转载,请注明出处。
如果你有更好的写法,可以留言和我交流下。

猜你喜欢

转载自blog.csdn.net/weixin_42881744/article/details/81705300
今日推荐