4.1 组件的定义及属性
组件是页面视图层(WXML)的基本组成单元,组件组合可以构建功能强大的页面结构。小程序框架为开发者提供了容器视图、基础内容、表单、导航、多媒体、地图、画布开放能力等8类(30多个)基础组件。组件的语法格式如下:
<标签名 属性名=”属性值”>内容…</标签名>
4.2 容器视图组件
容器视图组件是能容纳其他组件的组件,是构建小程序页面布局的基础组件,主要包括view、scroll -view 和swiper 组件。
4.2.1 view
view组件是块级组件,没有特殊功能,主要用于布局展示,相当于HTML中的div,是布局中最基本的用户界面(User Interface,UI)组件,通过设置view的CSS属性可以实现各种复杂的布局。
示例代码如下:
<view style="text-align:center">默认flex 布局</view >
<view style="display:flex">
<view style ="border:1px solid #f00; flex-grow:1 " >1 </view>
<view style = "border:1px solid #f00; flex-grow:1 " >2 </view>
<view style ="border:1px solid #f00; flex-grow:1 " >3 </view>
</view>
<view style="text-align:center">上下混合布局</view>
<view style="display:flex;flex-direction:column">
<view style="border:1px solid #f00;">1</view >
<view style="display:flex">
<view style="border:1px solid #f00;flex-grow:1">2 </view >
<view style ="border:1px solid #f00;flex-grow:2">3</view >
</view >
</view >
<view style="text-align:center">左右混合布局</view>
<view style="display:flex">
<view style = "border:1px solid #f00;flex-grow:1">1</view>
<view style ="display: flex;flex-direction:column; flex-grow:1">
<view style ="border:1px solid #f00; flex-grow:1">2 </view>
<view style ="border:1px solid #f00; flex-grow:2">3 </view>
</view>
</view>
运行截图:
4.2.2 scroll - view
通过设置scroll-view组件的相关属性可以实现滚动视图的功能,其属性如表:
4.2.3 swiper
swiper组件可以实现轮播图、图片预览、滑动页面等效果。
示例代码如下 :
<swiper indicator-dots='true' autoplay='true' interval='5000' duration='1000'>
<swiper-item>
<image src ="/pages/index/images/ww.jpg"></image>
</swiper-item>
<swiper-item>
<image src ="/pages/index/images/ee.jpg"></image>
</swiper-item>
<swiper-item>
<image src ="/pages/index/images/qq.jpg"></image>
</swiper-item>
</swiper>
运行截图:
4.3 基础内容组件
4.3.1 icon
icon组件即图标组件,通常用于表示一种状态,如success、info、warn、waiting、cancel等。
示例代码
index.wxml代码
<view>icon类型:
<block wx:for="{{iconType}}">
<icon type="{{item}}"/>{{item}}
</block>
</view>
<view>icon大小:
<block wx:for="{{iconSize}}">
<icon type="success" size="{{item}}"/>{{item}}
</block>
</view>
<view>icon颜色:
<block wx:for="{{iconColor}}">
<icon type="success" size="30" color="{{item}}"/>{{item}}
</block>
</view>
index.js代码:
data:{
iconType:["success","success_no_circle","info","warn","wait-ing","cancel","download","search","clear"],
iconSize:[10,20,30,40],
iconColor:['#f00','#0f0','#00f']
}
4.3.2 text
text组件用于展示内容,类似HTML中的<span>,text组件中的内容支持长按选中,支持转移字符“\”,属于行内元素。
示例代码:
index.wxml代码:
<block wx:for="{{x}}" wx:for-item="x">
<view class="aa">
<block wx:for="{{25 - x}}" wx:for-item="x">
<text decode = "{{true}}" space = "{{true}}"> </text>
</block>
<block wx:for="{{y}}" wx:for-item="y">
<block wx:if="{{y<=2 * x - 1}}">
<text>*</text>
</block>
</block>
</view>
</block>
<block wx:for="{{x}}" wx:for-item="x">
<view class="aa">
<block wx:for="{{19 + x}}" wx:for-item="x">
<text decode = "{{true}}" space = "{{true}}"> </text>
</block>
<block wx:for="{{y}}" wx:for-item="y">
<block wx:if="{{y<=11-2*x}}">
<text>*</text>
</block>
</block>
</view>
</block>
index.js代码:
Page({
data:{
x:[1,2,3,4,5],
y:[1,2,3,4,5,6,7,8,9]
}
})
4.3.3 progress
progress组件用于显示进度状态,如资源加载、用户资料完成度、媒体资源播放进度等。
progress组件属于块级元素。
示例代码:
<view>显示百分比</view>
<progress percent='80'show-info ='80'></progress>
<view>改变度 </view>
<progress percent='50'stroke-width ='2'></progress>
<view>自动显示进度条</view>
<progress percent ='80' active ></progress>
运行截图:
4.4 表单组件
4.4.1 button
buton组件用来实现用户和应用之间的交互,同时按钮的颜色起引导作用。
示例代码:
index.wxml代码
<button type = "default " >type;default </button>
<button type = "primary" >type:primary </button>
<button type = "warn" >type:warn </button>
<button type = "default" bindtap = 'buttonSize' size="{{size}}">改变size</button>
<button type = "default" bindtap = 'buttonPlain'Plain ="{{plain}}">改变plain</button>
<button type = "default" bindtap = 'buttonLoading'Loading="{{Loading}}">改变loading</button>
index.js代码:
Page({
data:{
size:'default',
plain:'false',
loading:'false'
},
buttonSize:function(){
if(this.data.size =="default")
this.setData({size:'mini'})
else
this.setData({size:'default'})
},
buttonPlain:function(){
this.setData({ plain:! this.data.plain})
},
buttonLoading:function(){
this.setData({ loading: ! this.data.loading})
}
})
运行截图:
4.4.2 radio
单选框用来从一组选项中选取一个选项。在小程序中,单选框由<radio-group/>(单项选择器)和<radio/>(单选项目)两个组件组合而成,一个包含多个<radio/>的<radio-group/>表示一组单选项,在同一组单选项中<radio/>是互斥的,当一个按钮被选中后,之前选中的按钮就变为非选。
示例代码:
index.wxml代码:
<view>选择您喜爱的城市:</view>
<radio-group bindchange="citychange">
<radio value="西安">西安</radio >
<radio value ="北京">北京</radio >
<radio value ="上海">上海</radio >
<radio value ="广州">广州</radio >
<radio value="深圳">深圳</radio>
</radio-group>
<view>你的选择:{{city}}</view>
<view>选择您喜爱的计算机语言:</view>
<radio-group class = "radio -group" bindchange ="radiochange">
<label class= "radio" wx:for ="{{radios}}">
<radio value = "{{item.value}} " checked = " {{item.checked}}"/>
{{item.name}}
</label>
</radio-group>
<view>你的选择:{{lang}}</view>
index.js代码:
Page({
data:{
radios:[
{ name:'java',value:'JAVA'},
{ name:'python',value:'Python',checked:'true'},
{ name:'php',value:'PHP'},
{ name:'swif',value:'Swif'},
],
},
citychange:function(e){
this.setData({city:e.detail.value});
},
radiochange:function(event){
this.setData({lang:event.detail.value});
console.log(event.detail.value)
}
})
运行截图:
4.4.3 checxbox
复选框用于从一组选项中选取多个选项,小程序中复选框由<checkbox-group/>(多项选择器)和<checkbox>(多选项目)两个组件组合而成。一个<checkbox-group/>表示一组选项,可以在一组选项中选中多个选项。它们的属性如表所示。
示例代码:
index.wxml代码:
<view>选择您想去的城市:</view>
<checkbox-group bindchange = "cityChange">
<label wx:for = "{{citys}}">
<checkbox value ="{{item.value}}" checked ='{{item.checked}}'>
{{litem.value}}
</checkbox>
</label>
</checkbox-group>
<view>您的选择是:{{city}}</view>
index.js代码:
Page({
city:",
data:{
citys:[
{ name:'km',value:'昆明'},
{ name:'sy',value:'三亚'},
{ name:'zh',value:'珠海'},
{ name:'dl',value:'大连'}]
},
cityChange:function(e){
console.log(e.detail.value);
var city = e.detail.value;
this.setData({city: city})
}
})
运行截图:
4.4.4 switch
switch 组件的作用类似开关选择器,其属性如表所示。
示例代码:
index.wxml代码:
<view>
<switch bindchange="sw1">{{var1}}</switch>
</view>
<view>
<switch checked bindchange="sw2">var2 }</switch>
</view>
<view>
<switch type="checkbox" bindchange ="sw3">{{var3}}|</switch>
</view>
index.js代码:
Page({
data:{
var1:'关',
var2:'开',
var3:'未选'
},
swl:function(e){
this.setData({var1:e.detail.value?'开':'关'})
},
sw2:function(e){
this.setData({var2:e.detail.value?'开':'关'})
},
sw3:function(e){
this.setData({var3:e.detail.value?'已选':'未选'})
}
})
运行截图:
4.4.5 slider
slider组件为滑动选择器,可以通过滑动来设置相应的值。
示例代码:
index.wxml代码:
<view>默认min=0 max=100 step =1 </view><slider></slider>
<view>显示当前值</view>
<slider show-value></slider><view>设置min=20 max=200 step=10</view ><slider min ='0'max='200'step ='10'show-value ></slider>
<view>背景条红色,已选定颜色绿色</view><slider color ="#f00" selected-color ='#f0'></slider >
<view>滑动改变icon 的大小</view>
<slider show-value bindchange='sliderchange'>
</slider><icon type="success" size='{{size}}'></icon >
index.js代码:
Page({
data:{
size:'20'
},
sliderchange:function(e){
this.setData({size:e.detail.value})
}
})
运行截图:
4.4.6 picker
picker组件为滚动选择器,当用户点击picker组件时,系统从底部弹出选择器供用户选择。picker组件目前支持5种选择器,分别是:selector(普通选择器)、multiSelector(多列选择器)、time(时间选择器)、date(日期选择器)、region(省市选择器)。
1.普通选择器
2.多列选择器
3.时间选择器、日期选择器
时间选择器属性表
日期选择器属性表
4.省市选择器
4.4.7 picker-view
picker-view组件为嵌入页面的滚动选择器。
示例代码:
index.wxml代码:
<view>当前日期:</view>
<picker-view indicator-style="height:50px" style="width:100%;height: 300px;"value="{{value}}"bindchange="bindchange">
<picker-view-column>
<view wx:for="{{years}}" style="line-height: 50px">{{item}}年</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{months}}" style="line-height: 50px">{{item}}月</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{days}}" style="line-height: 50px">{{item}}日</view>
</picker-view-column>
</picker-view>
index.js代码:
const date =new Date()
const years =[]
const months=[]
const days = []
for(let i =1900; i<=2050;i++){
years.push(i)
}
for(let i = 1;i<=12;i++){
months.push(i)
}
for(let i=1;i<=31;i++){
days.push(i)
}
Page({
data:{
years:years,
months:months,
days:days,
year:date.getFullYear(),
month:date.getMonth()+1,
day:date.getDate(),
value:[118.0,0],
},
bindChange:function(e){
const val =e.detail.value
console.log(val);
this.setUpdatePerformanceListener({
year:this.data.years[val[10]],
year:this.data.months[val[1]],
year:this.data.days[val[2]],
})
}
})
运行截图:
4.4.8 input
input组件为输入框,用户可以输入相应的信息。
示例代码:
index.wxml代码:
<input placeholder="这是一个可以自动聚焦的input" auto-focus/>
<input placeholder="这个只有在按钮点击的时候才能聚焦" focus="{{focus}}"/>
<button bindtap="bindButtonTap">使得输入框自动获取焦点</button>
<input maxlength="10" placeholder="最大输入长度为10"/>
<view class="section_title">你输入的是:{{inputValue}}</view>
<input bindinput="bindKeyInput" placeholder="输入同步到view中"/>
</view>
<input bindinput="bindReplaceInput" placeholder="连续的两个1会变成2"/>
<input password type="number"/>
<input password type="text"/>
<input type="digit" placeholder="带小数点的数字键盘"/>
<input type="idcard" placeholder="身份证输入键盘"/>
<input placeholder-style="color:red" placeholder="占位符字体是红色的"/>
index.js代码:
Page({
data:{
focus:false,
inputVlue:""
},
bindButtonTap:function(){
this.setData({
focus:true
})
},
bindKeyInput:function(e){
this.setData({
inputValue:e.detail.value
})
},
bindReplaceInput:function(e){
var value =e.detail.value
var pos =e.detail.cursor
if(pos != -1){
var left =e.datail.value.slice(0,pos)
pos =left.replace(/11/g,'2').length
}
return{
vaue:value.replace(/11/g,'2'),
cursor:pos
}
}
})
运行截图:
4.4.9 textarea
textarea组件为多行输入框组件,可以实现多行内容的输入。
示例代码:
index.wxml代码:
<textarea bindblur ="bindTextAreaBlur" auto-height placeholder="自动变高"/>
<textarea placeholder="placeholder 颜色是红色"placeholderstyle="color:red;"/>
<textarea placeholder="这是一个可以自动聚焦的textarea" auto-focus/>
<textarea placeholder="这个只有在按钮点击的时候才聚焦"focus="{{focus}}"/>
<button bindtap="bindButtonTap">使得输入框获取焦点</button >
<form bindsubmit="bindFormSubmit">
<textarea placeholder ="form 中的textarea" name ="textarea" />
<button form-type="submit">提交</button></form>
index.js代码:
Page({
data:{
height:10,
focus:false
},
bindButtonTap:function(){
this.setData({
focus:true
})
},
bindTextAreaBlur:function(e){
console.log(e.detail.value)
},
bindFormSubmit:function(e){
console.log(e.detail.value.textarea)
}
})
运行截图:
4.4.10 label
label组件为标签组件,用于提升表单组件的可用性。label组件支持使用for属性找到对应的id,或者将控件放在该标签下,当点击label组件时,就会触发对应的控件。for属性的优先级高于内部控件,内部有多个控件的时候默认触发第一个控件。
目前,label组件可以绑定的控件有<button/ >、<checkbox/ >、<radio/>、<switch/ >。
示例代码:
index.wxml代码:
<view><checkbox></checkbox>中国</view>
<view><label><checkbox> </checkbox >中国</label></view>
<checkbox-group bindchange="cityChange">
<label wx:for="{{citys}}">
<checkbox value ="{{item.value}}" checked = '{{item.checked}}'>
{{item.value}}</checkbox>
</label>
</checkbox-group>
<view>您的选择是:{{city}}</view>
index.js代码:
Page({
city:"",
data:{
citys:[
{name:'km',value:'昆明'},
{name:'sy',value:'三亚'},
{name:'zh',value:'珠海',checked:'true'},
{name:'dl',value:'大连'}]
},
cityChange:function(e){
console.log(e.detail.value);
var city =e.detail.value;
this.setData({city: city})
}
})
运行截图:
4.4.11 form
form组件为表单组件,用来实现将组件内的用户输入信息进行提交。当<form/ >表单中formType为submit的<button/ >组件时,会将表单组件中的value值进行提交。
示例代码:
index.wxml代码:
<form bindsubmit ="formSubmit " bindreset ="formReset ">
<view>姓名:
<input type="text"name="xm"/>
</view>
<view>性别:
<radio-group name="xb">
<label><radio value="男" checked/>男</label>
<label><radio value="女"/>女</label>
</radio-group>
</view>
<view>爱好:
<checkbox-group name="hobby">
<label wx:for="{{hobbies}}">
<checkbox value="{{item.value}}" checked='{{item.checked}}'>{{item.value}}</checkbox>
</label>
</checkbox-group>
</view>
<button formType='submit'>提交</button>
<button formrype='reset'>重置</button>
</form>
index.js代码:
Page({
hobby :"",
data:{
hobbies :[
{name:'jsj',value:'计算机',checked:'true'},
{name:'music',value:'听音乐'},
{name:'game',value:'玩电竟'},
{name:'swim',value:'游泳',checked:'true'}]
},
formSubmit:function(e){
console.log('form发生了submit事件,携带数据为:'.e.detail.value)
},
formReset:function(){
console.log('form发生了reset事件')
}
})
运行截图:
4.5 多媒体组件
多媒体组件包括image(图像)、audio(音频)、video(视频)、camera(相机)组件,使用这些组件,可以让页面更具有吸引力。
4.5.1 image
image组件为图像组件,与HTML中的 <img/ >类似,系统默认image组件的宽度为300 px、高度为2250 px, image组件的属性如表4-21所示。
1.缩放模式
示例代码:
index.wxml代码:
<block wx:for ="{{modes}}">
<view>当前图片的模式是:{{item}}</view>
<image mode ="{{item}}" src ="../index/images/maomao.jpg" style ="width:100%,height:100%"/>
</block>
index.js代码:
Page({
data:{
modes:['scaleToFill','aspectFit','aspectFill','widthFrix']
}
})
运行截图:
2.裁剪模式
示例代码:
index.wxml代码:
<block wx:for ="{{modes}}">
<view>当前图片的模式是:{{item}}</view>
<image mode ="{{item}}" src ="../index/images/maomao.jpg" style ="width:100%,height:100%"/>
</block>
index.js代码:
Page({
data:{
modes:['top','center','left','right','top_left','top_right','bottom_left','bottom_right']
}
})
运行截图:
4.5.2 audio
audio组件用来实现音乐播放、暂停等,其属性如下表
示例代码
index.wxml:
<audio src ="{{src}}" action="{{action}}" poster = "{{poster}}" name = "{{name}}" author ="{{author}} " loop controls></audio >
<button type="primary" bindtap='play'>播放</button >
<button type="primary" bindtap="pause">暂停</button >
<button type ="primary" bindtap="playRate">设置速率</button>
<button type="primary" bindtap="currentTime">设置当前时间(秒)</button>
index.js:
//audio.js
Page( {
data:{
poster:'http://.gtimg.cn/usic/hoto new/002R300x300M000003rsKF44Gyask.jpg?max age=2592000',
name:'此时此刻',
author:'许巍',
src:'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3? guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51 E1 E3 84E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
},
play:function(){
this.setData({
action:{
method: 'play'
}
})
},
pause:function(){
this.setData({
action:{
method: 'pause'
}
})
},
playRate:function(){
this.setData({
action:{
method:'setPlaybackRate',
data:10
}
})
console.log('当前速率:'+this.data.action.data)
},
currentTime:function(e){
this.setData({
action:{
method:'setCurrentTime',
data:120
}
})
}
})
运行截图:
4.5.3 video
video组件用来实现视频的播放、暂停等。视频的默认宽度为300 px,高度为225 px,
示例代码:
index.wxml代码:
<video src ="{{src}}" controls ></video >
<view class="btn-area">
<button bindtap="bindButtonTap">获取视频</button>
</view>
index.js代码:
Page({
data:{
src:"../index/images/lhj.mp4",
},
bindButtonTap:function(){
var that =this
wx.chooseVideo({
sourceType:['album','camera'],
maxDuration:60,
camera:['front','back'],
success:function(res){
that.setData({
src:res.tempFilePath
})
}
})
}
})
运行截图:
4.5.4 camera
camera组件为系统相机组件,可以实现拍照或录像功能。在一个页面中,只能有一个camera组件。在开发工具中运行时,使用电脑摄像头实现拍照或录像;在手机中运行时,使用手机前后摄像头实现拍照或录像。
示例代码:
index.wxml代码:
<camera device -position ="back" flash ="off" binderror ="error"
style="width:100%;height:350px;"></camera>
<button type ="primary" bindtap ="takePhoto" >拍照</button ><view>预览</view >
<image mode ="widthFix" src ="{{src}}"></image>
index.js代码:
Page({
takePhoto(){
const ctx=wx.createCameraContext()//创建并返回 camera上下文对象/拍照,成功则返回图片
ctx.takePhoto({
quality:' high',
success:(res)=>{
this.setData({
src:res.tempImagePath
})
}
})
},
error(e){
console.log(e.detail)
}
})
运行截图:
4.6 其他组件
4.6.1 map
map组件用于在页面中显示地图或路径,常用于LBS(基于位置服务)或路径指引,功能相对百度地图、高德地图较简单,目前具备绘制图标、路线、半径等能力,不能在croll-view、swiper、picker-view、movable-view组件中使用。
map组件的属性
map组件的markers属性
map组件的polyline属性
示例代码:
index.wxml代码:
<map id = "map"
longitude="108.9200"
latitude="34.1550"
scale="14"
controls="{{controls}}"
bindcontroltap="controltap"
markers="{{markers}}"
bindmarkertap="markertap"
polyline="{{polyline}}"
bindregionchange="regionchange"
show-location
style="width:100%;height:300px;">
</map>
index.js代码:
Page({
data:{
markers:[{
iconPath:"/pages/dw.png",
id:0,
longitude:"108.9290",
latitude:"34.1480",
width:50,
height:50
}],
polyline:[{
polyline:[
{
longitude:"108.9200",
latitude:"34.1400",
},
{
longitude:"108.9200",
latitude:"34.1500",
},
{
longitude:"108.9200",
latitude:"34.1700",
},
],
color:"#00ff00",
width:2,
dottedLine:true
}],
controls:[{
id:1,
iconPath:'/pages/dw.png',
position:{
left:0,
top:300,
width:30,
height:30
},
chickable:true
}]
},
regionchange(e){
console.log(e.type)
},
markertap(e){
console.log(e.markerId)
},
controltap(e){
console.log(e.controlId)
}
})
运行截图:
4.6.2 canvas
canvas组件用来绘制图形,相当于一块无色透明的普通图布。canvas组件本身并没有绘图能力,仅仅是图形容器,通过绘图API实现绘图功能。
示例代码:
index.wxml代码:
<canvas canvas-id ="myCanvas" style ="border: 1px solid red;"/>
index.js代码:
Page({
onLoad:function(options){
var ctx=wx.createCanvasContext('myCanvas')
ctx.setFillStyle('green')
ctx.fillRect(10,10,200,100)
ctx.draw()
}
})
运行截图: