自定义组件和小程序UI组件库

一、自定义组件

1. 创建components文件夹以及组件tag文件夹

2. 右击新建一个component

  • 新建component才是定义一个组件


3. 首先需要在 json 文件中进行自定义组件声明(将 component 字段设为 true 可将这一组文件设为自定义组件)

//  tag.json
{
    "component": true,
    "usingComponents": {}
}

4.在 wxml 文件中编写组件模板

// tag.wxml
<view class="item-wrap">
    <view class="left-img">
        <image src="{{imgUrl}}"></image>
    </view>
    <view class="right-text">
        <text class="dishName">{{dishName}}</text>
        <text class="shopName">{{shopName}}</text>
        <text class="dishPrice">¥{{dishPrice}}</text>
    </view>
</view>

5. 在自定义组件的 js 文件中,需要使用 Component() 来注册组件,并提供组件的属性定义、内部数据和自定义方法

  • 组件的属性值和内部数据将被用于组件 wxml 的渲染,其中,属性值是可由组件外部传入的,在properties中去绑定属性值
// tag.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        id: {
            type: Number,
        },
        imgUrl: {
            type: String,
            value: ''
        },
        dishName: {
            type: String,
            value: ''
        },
        shopName: {
            type: String,
            value: ''
        },
        dishPrice: {
            type: String,
            value: ''
        }
    },

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

    },

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

6. 在需要使用的页面的json文件中去注册组件

  • "组件标签名":"组件的地址"
// index.json
{
  "usingComponents": {
    "mytag": "../../components/tag/tag"
  },
  "enablePullDownRefresh": true
}

7. 在需要使用组件的页面的wxml文件中去使用组件

  • 设置在properties中绑定的属性值,可以将属性值传到组件中去
<view class="menu">
    <mytag wx:for="{{productList}}" wx:key="index" wx:for-item="menuItem" imgUrl="{{menuItem.picture}}" dishName="{{menuItem.product}}" shopName="{{menuItem.shop}}" dishPrice="{{menuItem.price}}" bindtap="openDishHandle" data-shopId="{{menuItem.id}}"></mytag>
</view>

二、Vant Weapp轻量级UI组件库

1. 通过npm命令行安装组件库

  • 在项目所在的文件夹中去打开命令行
npm i @vant/weapp -S --production

2.构建 npm 包

(1)打开微信开发者工具,右上角点击 详情 --> 本地设置 --> 勾选使用npm模块

3.打开微信开发者工具,左上角点击 工具 --> 构造npm


4. 若点击构造npm时报错,npm构造文件不存在,则需要对npm进行初始化

  • 在项目所在的文件夹中去打开命令行
npm init -y

初始化完成以后,再去构造npm

5. 使用vant weapp组件

(1)在json文件中引入
"usingComponents": {
  "van-button": "@vant/weapp/button/index"
}
(2)在wxml文件中使用
<van-button type="default">默认按钮</van-button>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容