一特愿、自定義組件
1. 創(chuàng)建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() 來注冊組件苔货,并提供組件的屬性定義妈候、內部數(shù)據(jù)和自定義方法
- 組件的屬性值和內部數(shù)據(jù)將被用于組件 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: ''
}
},
/**
* 組件的初始數(shù)據(jù)
*/
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)打開微信開發(fā)者工具幔虏,右上角點擊 詳情 --> 本地設置 --> 勾選使用npm模塊
3.打開微信開發(fā)者工具纺念,左上角點擊 工具 --> 構造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>