微信小程序自定义组件

组件的初步认知。
首先组件也是由js,json,wxml,wxss四个文件组成,和page页面一样,只不过组件js文件的写法跟page有所区别。以下组件的js文件,可以看下。接下来我们写一个简单的组件infoCell,效果图如下。

截屏2021-01-28 下午4.52.48.png
Component({
  /**
   * 组件的属性列表
   */
  // 在这里itemDic是为了外部引用组件时,把外部的数据传进来。
  // 不仅要在属性properties里面定义并声明其类型,还要在data里面声明。
  properties: {
     itemDic:{
       type:JSON,
       value:''
     }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // itemDic:{"title":"姓名","subTitle":"请输入会员姓名","xing":false}
    itemDic:{},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    cellTap:function(e){
      // console.log(e.currentTarget)
    }
  }
})

组件的json文件写法其实很简单

{
  "component": true
}

接下来就是wxml,wxss文件里面一些控件的编写,就不叙述了。直接上代码吧。


  
    {{itemDic.title}}
    
  
  
    {{itemDic.subTitle}}
  


.cell {
  width: 100%;
  height: 90rpx;
  display: flex;
  flex-direction: row;
  border-bottom: 1rpx solid #e5e5e5;
  vertical-align: center; 
  align-items: center;    
  justify-content: center; 
}
.leftCell{
  margin-left: 20rpx;
  display: flex;
  flex-direction: row;
  flex: 1;
}
.cellTitle {
  color: rgba(0, 0, 0, 0.616);
  font: 15rpx;
}
.xing{
  color: red;
  margin-left: 10rpx;
}
.cellPlaceHoder {
  margin-right: 30rpx;
  font: 12rpx;
  color: rgba(0, 0, 0, 0.425);
}

那么组件写完了,该怎么使用呢?

首先,要在页面中引入组件。这里,我以newCust这个页面为例子。
在newCust.json中引入如下

{
  "navigationBarTitleText": "新客建档",
  "usingComponents": {
    "infoCell": "../../component/infoCell/infoCell",
    "selectCell": "../../component/selectCell/selectCell",
    "radioCell": "../../component/radioCell/radioCell"
  
  }
}

引入时,注意下图提示内容:


Snip20210128_1.png

就这样,组件就引入了页面,可以在页面中直接使用了。

 
      
    

你可能感兴趣的:(微信小程序自定义组件)