微信小程序组件自定义和使用

组件介绍

Component像页面一样由wxml、wxss、js和json4个文件组成,且需要把这4个文件放在同一个目录中。与页面不一样的是,Component中的构造函数(也可以称构造器)是Component({}),而页面中的构造函数是Page({})。要编写一个自定义组件,首先需要在json文件中进行自定义组件声明(将component字段设为true可这一组文件设为自定义组件)。

使用组件

使用已注册的自定义组件前,首先要在页面的 json 文件中进行引用声明。此时需要提供每个自定义组件的标签名和对应的自定义组件文件路径。

{
  "usingComponents": {
    "component": "/components/component/component"
  }
}

在page页面下添加声明过的自定义组件,

<component></component>

实战

empty.js


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

  /**
   * 组件的初始数据
   */
  data: {
  },

  /**
   * 组件的方法列表
   */
  methods: {
  }
});

empty.json

{
    "component": true
}

empty.scss,empty.wxss

.empty {
    margin-top: 100rpx;
    text-align: center;
    .empty-img {
        width: 220rpx;
        height: 175rpx;
    }
    .empty-text {
        font-size: 20rpx;
        color: #999999;
    }
}
.empty {
  margin-top: 100rpx;
  text-align: center;
}

.empty .empty-img {
  width: 220rpx;
  height: 175rpx;
}

.empty .empty-text {
  font-size: 20rpx;
  color: #999999;
}

empty.wxml

<view class="empty">
    <image  class="empty-img" src="/images/common/empty.png"/>
    <view class="empty-text">暂无数据~</view>
</view>

使用

index.json

{
  "usingComponents": {
    "emptyContent": "/components/empty/empty"
  }
}

index.wxml

<emptyContent></emptyContent>

posted @ 2020-05-15 10:07  TBHacker  阅读(351)  评论(0编辑  收藏  举报