天天看點

從0到一開發微信小程式(4)—小程式元件

文章目錄

  • ​​其他相關文章​​
  • ​​1、元件​​
  • ​​1.1、基礎視圖​​
  • ​​1.1.1、view​​
  • ​​1.1.1.1、屬性說明​​
  • ​​1.1.2、text​​
  • ​​1.1.3、image​​
  • ​​支援長按識别的碼​​
  • ​​1.2、滑件視圖容器Swiper(焦點輪播圖)​​
  • ​​1.3、滾動視圖區域(scroll-view)​​
  • ​​1.4、圖示(icon)​​
  • ​​1.5、表單(form )​​
  • ​​1.6、按鈕(button)​​
  • ​​1.7、輸入框(input)​​
  • ​​1.8、picker(滾動選擇器)​​
  • ​​1.8.1、普通選擇器​​
  • ​​展示效果:​​
  • ​​1.8.2、多列選擇器​​
  • ​​展示效果:​​
  • ​​1.8.3、時間選擇器​​
  • ​​展示效果:​​
  • ​​1.8.4、日期選擇器​​
  • ​​展示效果:​​
  • ​​1.8.5、省市區選擇器​​
  • ​​展示效果:​​
  • ​​1.9、slider(滑動選擇器)​​
  • ​​使用形式​​
  • ​​常用屬性​​
  • ​​測試代碼:​​
  • ​​展示效果:​​
  • ​​1.10、表單其他元件​​
  • ​​checkbox(複選框 )​​
  • ​​radio(單選項目)​​
  • ​​label(标簽)​​
  • ​​switch(開關選擇器)​​
  • ​​屬性清單​​
  • ​​textarea(多行輸入框)​​
  • ​​1.11、navigator(頁面之間跳轉)​​
  • ​​常用屬性說明​​
  • ​​擴充:生命周期函數​​
  • ​​1.12、audio(音樂)​​
  • ​​切換音樂​​
  • ​​1.13、video(視訊)​​
  • ​​屬性說明​​
  • ​​測試代碼:​​
  • ​​展示效果:​​
  • ​​1.14、camera(拍照)​​
  • ​​屬性說明​​
  • ​​1.15、map(地圖)​​
  • ​​屬性說明​​
  • ​​展示效果:​​
  • ​​1.16、進度條(progress)​​
  • ​​屬性說明​​

其他相關文章

從0到一開發微信小程式(1)——申請賬号并安裝開發環境

從0到一開發微信小程式(2)——開發第一個小程式

從0到一開發微信小程式(3)—小程式架構配置

從0到一開發微信小程式(4)—小程式元件

從0到一開發微信小程式(5)—小程式WXML

從0到一開發微信小程式(6)—小程式常用API ——正在書寫中

從0到一開發微信小程式(7)—小程式元件庫(提高開發效率)

從0到一開發微信小程式(8)—實戰一個商城項目——正在書寫中

1、元件

1.1、基礎視圖

小程式中常用的基礎視圖,有三種,分别是view,text,image

view:視圖容器

text:文本

image:圖檔。支援 JPG、PNG、SVG、WEBP、GIF 等格式,2.3.0 起支援雲檔案ID。

1.1.1、view

view的顯示效果跟div是一樣的,我們可以了解為它就是一個html中的div,它屬于塊級元素

1.1.1.1、屬性說明

屬性 類型 預設值 必填 說明
hover-class string none 指定按下去的樣式類。當 hover-class=“none” 時,沒有點選态效果
hover-stop-propagation boolean false 指定是否阻止本節點的祖先節點出現點選态
hover-start-time number 50 按住後多久出現點選态,機關毫秒
hover-stay-time number 400 手指松開後點選态保留時間,機關毫秒

注意:如果需要滾動視圖,請使用scroll-view

測試代碼:

建立一個views頁面,在views.wxml中添加:

<view class="container">
  <view class="page-body">
    <view class="page-section">
      <view class="page-section-title">
        <text>flex-direction: row\n橫向布局</text>
      </view>
      <view class="page-section-spacing">
        <view class="flex-wrp" style="flex-direction:row;">
          <view class="flex-item demo-text-1">A</view>
          <view class="flex-item demo-text-2">B</view>
          <view class="flex-item demo-text-3">C</view>
        </view>
      </view>
    </view>
  </view>
</view>      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.1.2、text

文本,承載頁面文本資訊,類似span的功能

<text>文本1</text>
<text>文本2</text>      

text 是行内元素

溫馨提示:

  1. text 元件内隻支援 text 嵌套
  2. 除了文本節點以外的其他節點都無法長按選中

1.1.3、image

圖檔。支援 JPG、PNG、SVG、WEBP、GIF 等格式

屬性 類型 預設值 必填 說明
src string 圖檔資源位址
mode string scaleToFill 圖檔裁剪、縮放的模式
webp boolean false 預設不解析 webP 格式,隻支援網絡資源
lazy-load boolean false 圖檔懶加載,在即将進入一定範圍(上下三屏)時才開始加載
show-menu-by-longpress boolean false 長按圖檔顯示發送給朋友、收藏、儲存圖檔、搜一搜、打開名片/前往群聊/打開小程式(若圖檔中包含對應二維碼或小程式碼)的菜單。
binderror eventhandle 當錯誤發生時觸發,event.detail = {errMsg}
bindload eventhandle 當圖檔載入完畢時觸發,event.detail = {height, width}

在上面中,model的屬性值又有很多種

合法值 說明
scaleToFill 縮放模式,不保持縱橫比縮放圖檔,使圖檔的寬高完全拉伸至填滿 image 元素
aspectFit 縮放模式,保持縱橫比縮放圖檔,使圖檔的長邊能完全顯示出來。也就是說,可以完整地将圖檔顯示出來。
aspectFill 縮放模式,保持縱橫比縮放圖檔,隻保證圖檔的短邊能完全顯示出來。也就是說,圖檔通常隻在水準或垂直方向是完整的,另一個方向将會發生截取。
widthFix 縮放模式,寬度不變,高度自動變化,保持原圖寬高比不變
heightFix 縮放模式,高度不變,寬度自動變化,保持原圖寬高比不變
top 裁剪模式,不縮放圖檔,隻顯示圖檔的頂部區域
bottom 裁剪模式,不縮放圖檔,隻顯示圖檔的底部區域
center 裁剪模式,不縮放圖檔,隻顯示圖檔的中間區域
left 裁剪模式,不縮放圖檔,隻顯示圖檔的左邊區域
right 裁剪模式,不縮放圖檔,隻顯示圖檔的右邊區域
top left 裁剪模式,不縮放圖檔,隻顯示圖檔的左上邊區域
top right 裁剪模式,不縮放圖檔,隻顯示圖檔的右上邊區域
bottom left 裁剪模式,不縮放圖檔,隻顯示圖檔的左下邊區域
bottom right 裁剪模式,不縮放圖檔,隻顯示圖檔的右下邊區域

show-menu-by-longpress的屬性值對應的字段資訊為:

支援長按識别的碼

類型 說明
小程式碼
微信個人碼
企業微信個人碼
普通群碼 指僅包含微信使用者的群
互通群碼 指既有微信使用者也有企業微信使用者的群
公衆号二維碼

提示:

  1. image元件預設寬度320px、高度240px
  2. image元件中二維碼/小程式碼圖檔不支援長按識别。僅在 wx.previewImage 中支援長按識别
  3. image元件進行縮放時,計算出來的寬高可能帶有小數,在不同 webview 核心下渲染可能會被抹去小數部分

測試代碼:

新增一個頁面:image-view,然後在image-view.js中添加

Page({
  data: {
    array: [{
      mode: 'scaleToFill',
      text: 'scaleToFill:不保持縱橫比縮放圖檔,使圖檔完全适應'
    }, {
      mode: 'aspectFit',
      text: 'aspectFit:保持縱橫比縮放圖檔,使圖檔的長邊能完全顯示出來'
    }, {
      mode: 'aspectFill',
      text: 'aspectFill:保持縱橫比縮放圖檔,隻保證圖檔的短邊能完全顯示出來'
    }, {
      mode: 'top',
      text: 'top:不縮放圖檔,隻顯示圖檔的頂部區域'
    }, {
      mode: 'bottom',
      text: 'bottom:不縮放圖檔,隻顯示圖檔的底部區域'
    }, {
      mode: 'center',
      text: 'center:不縮放圖檔,隻顯示圖檔的中間區域'
    }, {
      mode: 'left',
      text: 'left:不縮放圖檔,隻顯示圖檔的左邊區域'
    }, {
      mode: 'right',
      text: 'right:不縮放圖檔,隻顯示圖檔的右邊邊區域'
    }, {
      mode: 'top left',
      text: 'top left:不縮放圖檔,隻顯示圖檔的左上邊區域'
    }, {
      mode: 'top right',
      text: 'top right:不縮放圖檔,隻顯示圖檔的右上邊區域'
    }, {
      mode: 'bottom left',
      text: 'bottom left:不縮放圖檔,隻顯示圖檔的左下邊區域'
    }, {
      mode: 'bottom right',
      text: 'bottom right:不縮放圖檔,隻顯示圖檔的右下邊區域'
    }],
    src: 'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg'
  },
  imageError: function(e) {
    console.log('image3發生error事件,攜帶值為', e.detail.errMsg)
  }
})      

在image-view.wxml中添加

<view class="page">
  <view class="page__hd">
    <text class="page__title">image</text>
    <text class="page__desc">圖檔</text>
  </view>
  <view class="page__bd">
    <view class="section section_gap" wx:for="{{array}}" wx:for-item="item">
      <view class="section__title">{{item.text}}</view>
      <view class="section__ctn">
        <image style="width: 200px; height: 200px; background-color: #eeeeee;" mode="{{item.mode}}" src="{{src}}"></image>
      </view>
    </view>
  </view>
</view>      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.2、滑件視圖容器Swiper(焦點輪播圖)

Swiper常用屬性說明:

屬性 類型 預設值 必填 說明
indicator-dots boolean false 是否顯示面闆訓示點
indicator-color color rgba(0, 0, 0, .3) 訓示點顔色
indicator-active-color color #000000 目前選中的訓示點顔色
autoplay boolean false 是否自動切換
interval number 5000 自動切換時間間隔
duration number 500 滑動動畫時長
circular boolean false 是否采用銜接滑動
vertical boolean false

滑動視圖相信大家應該看過,往左右拉的那種圖吧,我們來實作一版,

簡單版:建立一個swiper頁面,再swiper.wxml中添加

<!-- swiper.wxml -->
<view>
  <swiper class="swiper">
    <swiper-item>
      <image mode="widthFix" src="../../images/1.jpg"></image>
    </swiper-item>
    <swiper-item>
      <image mode="widthFix" src="../../images/2.jpg"></image>
    </swiper-item>
    <swiper-item>
      <image mode="widthFix" src="../../images/3.jpg"></image>
    </swiper-item>
  </swiper>
</view>      

在swiper.wxss中添加:(同時設定圖檔樣式充滿全屏,因為圖檔預設大小:寬度320px、高度240px)

/* swiper.wxss */
image{
  width: 100%;
}      

展示效果:

從0到一開發微信小程式(4)—小程式元件
從0到一開發微信小程式(4)—小程式元件

一直向右拉,依次會出現1.jpg,2.jpg,3.jpg的圖

複雜版:自動每隔5秒向下換圖,建立頁面swiper-complex,其中swiper-complex.wxml中添加

<!-- swiper-complex.wxml -->
<view>
  <swiper 
  class="swiper"
  indicator-dots="{{ swiperOptions.indicatorDots }}"
  indicator-color="{{ swiperOptions.indicatorColor }}"
  indicator-active-color="{{ swiperOptions.indicatorActiveColor }}"
  autoplay="{{ swiperOptions.autoplay }}"
  interval="{{ swiperOptions.interval }}"
  duration="{{ swiperOptions.duration }}"
  circular="{{ swiperOptions.circular }}"
  vertical="{{ swiperOptions.vertical }}"
  >
    <swiper-item>
      <image mode="widthFix" src="../../images/1.jpg"></image>
    </swiper-item>
    <swiper-item>
      <image mode="widthFix" src="../../images/2.jpg"></image>
    </swiper-item>
    <swiper-item>
      <image mode="widthFix" src="../../images/3.jpg"></image>
    </swiper-item>
  </swiper>
</view>      

swiper-complex.js中添加

// swiper-complex.js
Page({
  data: {
    swiperOptions:{
      indicatorDots:true,
      indicatorColor:"#fff",
      indicatorActiveColor:"#f00",
      autoplay:true,
      interval:5000,
      duration:1000,
      circular:true,
      vertical:true
     }
   }
})      

1.3、滾動視圖區域(scroll-view)

功能描述

  • 可滾動視圖區域。使用豎向滾動時,需要給scroll-view一個固定高度,通過 WXSS 設定 height。元件屬性的長度機關預設為px,2.4.0起支援傳入機關(rpx/px)。

屬性說明:

屬性 類型 預設值 必填 說明
scroll-x boolean false 允許橫向滾動
scroll-y boolean false 允許縱向滾動
upper-threshold number/string 50 距頂部/左邊多遠時,觸發 scrolltoupper 事件
lower-threshold number/string 50 距底部/右邊多遠時,觸發 scrolltolower 事件
scroll-top number/string 設定豎向滾動條位置
scroll-left number/string 設定橫向滾動條位置
scroll-into-view string 值應為某子元素id(id不能以數字開頭)。設定哪個方向可滾動,則在哪個方向滾動到該元素
scroll-with-animation boolean false 在設定滾動條位置時使用動畫過渡
enable-back-to-top boolean false iOS點選頂部狀态欄、安卓輕按兩下标題欄時,滾動條傳回頂部,隻支援豎向
enable-flex boolean false 啟用 flexbox 布局。開啟後,目前節點聲明了 ​

​display: flex​

​ 就會成為 flex container,并作用于其孩子節點。
scroll-anchoring boolean false 開啟 scroll anchoring 特性,即控制滾動位置不随内容變化而抖動,僅在 iOS 下生效,安卓下可參考 CSS ​

​overflow-anchor​

​ 屬性。
enable-passive boolean false 開啟 passive 特性,能優化一定的滾動性能
refresher-enabled boolean false 開啟自定義下拉重新整理
refresher-threshold number 45 設定自定義下拉重新整理門檻值
refresher-default-style string “black” 設定自定義下拉重新整理預設樣式,支援設定 ​

​black &#124; white &#124; none​

​, none 表示不使用預設樣式
refresher-background string “#FFF” 設定自定義下拉重新整理區域背景顔色
refresher-triggered boolean false 設定目前下拉重新整理狀态,true 表示下拉重新整理已經被觸發,false 表示下拉重新整理未被觸發
enhanced boolean false 啟用 scroll-view 增強特性,啟用後可通過 ScrollViewContext
操作 scroll-view
bounces boolean true iOS 下 scroll-view 邊界彈性控制 (同時開啟 enhanced 屬性後生效)
show-scrollbar boolean true 滾動條顯隐控制 (同時開啟 enhanced 屬性後生效)
paging-enabled boolean false 分頁滑動效果 (同時開啟 enhanced 屬性後生效)
fast-deceleration boolean false 滑動減速速率控制 (同時開啟 enhanced 屬性後生效)
binddragstart eventhandle 滑動開始事件 (同時開啟 enhanced 屬性後生效) detail { scrollTop, scrollLeft }
binddragging eventhandle 滑動事件 (同時開啟 enhanced 屬性後生效) detail { scrollTop, scrollLeft }
binddragend eventhandle 滑動結束事件 (同時開啟 enhanced 屬性後生效) detail { scrollTop, scrollLeft, velocity }
bindscrolltoupper eventhandle 滾動到頂部/左邊時觸發
bindscrolltolower eventhandle 滾動到底部/右邊時觸發
bindscroll eventhandle 滾動時觸發,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
bindrefresherpulling eventhandle 自定義下拉重新整理控件被下拉
bindrefresherrefresh eventhandle 自定義下拉重新整理被觸發
bindrefresherrestore eventhandle 自定義下拉重新整理被複位
bindrefresherabort eventhandle 自定義下拉重新整理被中止

測試代碼:

建立一個頁面score-view,在score-view.js中添加

const order = ['demo1', 'demo2', 'demo3']

Page({
  onShareAppMessage() {
    return {
      title: 'scroll-view',
      path: '/pages/scroll-view/scroll-view'
    }
  },

  data: {
    toView: 'green'
  },

  upper(e) {
    console.log(e)
  },

  lower(e) {
    console.log(e)
  },

  scroll(e) {
    console.log(e)
  },

  scrollToTop() {
    this.setAction({
      scrollTop: 0
    })
  },

  tap() {
    for (let i = 0; i < order.length; ++i) {
      if (order[i] === this.data.toView) {
        this.setData({
          toView: order[i + 1],
          scrollTop: (i + 1) * 200
        })
        break
      }
    }
  },

  tapMove() {
    this.setData({
      scrollTop: this.data.scrollTop + 10
    })
  }
})      

score-view.wxml中添加

<view class="container">
  <view class="page-body">
    <view class="page-section">
      <view class="page-section-title">
        <text>Vertical Scroll\n縱向滾動</text>
      </view>
      <view class="page-section-spacing">
        <scroll-view scroll-y="true" style="height: 300rpx;" bindscrolltoupper="upper" bindscrolltolower="lower" bindscroll="scroll" scroll-into-view="{{toView}}" scroll-top="{{scrollTop}}">
          <view id="demo1" class="scroll-view-item demo-text-1"></view>
          <view id="demo2"  class="scroll-view-item demo-text-2"></view>
          <view id="demo3" class="scroll-view-item demo-text-3"></view>
        </scroll-view>
      </view>
    </view>
    <view class="page-section">
      <view class="page-section-title">
        <text>Horizontal Scroll\n橫向滾動</text>
      </view>
      <view class="page-section-spacing">
        <scroll-view class="scroll-view_H" scroll-x="true" bindscroll="scroll" style="width:">
          <view id="demo1" class="scroll-view-item_H demo-text-1"></view>
          <view id="demo2"  class="scroll-view-item_H demo-text-2"></view>
          <view id="demo3" class="scroll-view-item_H demo-text-3"></view>
        </scroll-view>
      </view>
    </view>
  </view>
</view>      

score-view.wxss中添加

.page-section-spacing{
  margin-top: 60rpx;
}
.scroll-view_H{
  white-space: nowrap;
}
.scroll-view-item{
  height: 300rpx;
}
.scroll-view-item_H{
  display: inline-block;
  width: 100%;
  height: 300rpx;
}      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.4、圖示(icon)

圖示元件,其實就是字型圖示效果,但是這裡所提供的隻有最常用的幾個。

圖示的使用方式為:

​<icon type="xxx"></icon>​

字型圖示屬性為:

屬性 類型 預設值 必填 說明
type string icon的類型,有效值:success, success_no_circle, info, warn, waiting, cancel, download, search, clear
size number/string 23 icon的大小,機關預設為px,2.4.0起支援傳入機關(rpx/px),2.21.3起支援傳入其餘機關(rem 等)。
color string icon的顔色,同 css 的color

建立一個頁面icon,其中icon.wxml中添加:

<icon type="success" size="50" color="red"></icon>
<icon type="success_no_circle" size="50"></icon>
<icon type="info" size="50"></icon>
<icon type="warn" size="50"></icon>
<icon type="waiting" size="50"></icon>
<icon type="cancel" size="50"></icon>
<icon type="download" size="50"></icon>
<icon type="search" size="50"></icon>
<icon type="clear" size="50"></icon>      

展示效果為:

從0到一開發微信小程式(4)—小程式元件

1.5、表單(form )

  • 表單,将使用者輸入的資訊送出到伺服器
  • 小程式的表單與html的表單基本一緻
  • 表單頁面随處可見,比如:登入,注冊,資訊修改,添加等

我們這裡拿一個常用的登入頁面來說:

  • 我們實作一個簡單的登入注冊,一般需要三個元件:
  • form 表單
  • button 按鈕
  • input 輸入框

建立一個頁面login,在login.wxml中添加:

<view class="login">
  <form>
    <input placeholder="請輸入使用者名" />
    <input placeholder="請輸入密碼" />
    <button type="primary">登入</button>
  </form>
</view>      

在login.wxss中添加

.login{
  margin-top: 100rpx;
}
input{
  border: 1px solid #999;
  border-radius: 5px;
  margin: 10px;
  padding-left: 10px;
  height: 70rpx;
}      

展示效果為:

從0到一開發微信小程式(4)—小程式元件

1.6、按鈕(button)

  • 小程式的 button 按鈕與 html 的非常類似,但是小程式的功能要更強大一些

使用形式:

​<button>按鈕</button>​

按鈕屬性:

屬性 類型 預設值 必填 說明
type string default 按鈕的樣式類型
size string default 按鈕的大小
plain boolean false 按鈕是否镂空,背景色透明
disabled boolean false 是否禁用
loading boolean false 名稱前是否帶 loading 圖示
form-type string 用于 form元件,點選分别會觸發form元件的 submit/reset 事件

其中type屬性又分為:

合法值 說明
primary 綠色
default 白色
warn 紅色

size屬性分為:

合法值 說明
default 預設大小
mini 小尺寸

測試代碼:

<button>按鈕</button>
<button type="default">按鈕</button>
<button type="primary">按鈕</button>
<button type="warn">按鈕</button>
<button type="primary" size="default">按鈕</button>
<button type="primary" size="mini">按鈕</button>
<button type="primary" plain>按鈕</button>
<button type="primary" disabled>按鈕</button>
<button type="primary" loading>按鈕</button>
<button type="primary" form-type="submit">按鈕</button>      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.7、輸入框(input)

  • 輸入框是input, 與html的輸入框類似,但是增加了很多新的功能

使用形式:

​<input/>​

屬性說明:

屬性 類型 預設值 必填 說明
value string 輸入框的初始内容
placeholder string 輸入框為空時占位符
password boolean false 是否是密碼類型
disabled boolean false 是否禁用
maxlength number 140 最大輸入長度,設定為 -1 的時候不限制最大長度
focus boolean false 擷取焦點
type string text input 的類型
confirm-type string done 設定鍵盤右下角按鈕的文字,僅在type='text’時生效

type 屬性詳解

合法值 說明
text 文本輸入鍵盤
number 數字輸入鍵盤
idcard 身份證輸入鍵盤
digit 帶小數點的數字鍵盤
nickname 昵稱輸入鍵盤

confirm-type屬性詳解

合法值 說明
send 右下角按鈕為“發送”
search 右下角按鈕為“搜尋”
next 右下角按鈕為“下一個”
go 右下角按鈕為“前往”
done 右下角按鈕為“完成”

測試代碼:

<input />
<input value="測試資訊"/>
<input placeholder="請輸入使用者名"/>
<input placeholder="請輸入密碼" password/>
<input placeholder="請輸入密碼" disabled/>
<input placeholder="文本" maxlength="10"/>
<input placeholder="文本" focus/>
<input placeholder="文本" type="text"/>
<input placeholder="文本" type="number"/>
<input placeholder="文本" type="idcard"/>
<input placeholder="文本" type="digit"/>
<input placeholder="文本" type="nickname"/>
<input placeholder="文本" type="text" confirm-type="send"/>
<input placeholder="文本" type="text" confirm-type="search"/>
<input placeholder="文本" type="text" confirm-type="next"/>
<input placeholder="文本" type="text" confirm-type="go"/>
<input placeholder="文本" type="text" confirm-type="done"/>      
input{
  border: 1px solid #999;
  height: 80rpx;
  margin: 10px;
  padding-left: 10px;
}      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.8、picker(滾動選擇器)

  • 選擇器的種類有很多,分别為:
  1. 普通選擇器
  2. 多列選擇器
  3. 時間選擇器
  4. 日期選擇器
  5. 省市區選擇器

1.8.1、普通選擇器

指定mode屬性為selector,或者預設不指定mode

<view>普通選擇器</view>
<picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}">
  <view class="picker">
     目前選擇:{{array[index]}}
  </view>
</picker>      

選擇器展示效果需要配合邏輯

Page({
  data: {
    array: ['美國', '中國', '巴西', '日本'],
    index: 0
   },
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.8.2、多列選擇器

指定mode屬性為multiSelector

<view>多列選擇器</view>
<picker mode="multiSelector" bindchange="bindMultiPickerChange" value="{{multiIndex}}" range="{{multiArray}}">
  <view class="picker">
     目前選擇:{{multiArray[0][multiIndex[0]]}},{{multiArray[1][multiIndex[1]]}},{{multiArray[2][multiIndex[2]]}}
  </view>
</picker>      
Page({
  data: {
    multiArray: [
       ['無脊柱動物', '脊柱動物'],
       ['扁性動物', '線形動物', '環節動物', '軟體動物', '節肢動物'],
       ['豬肉縧蟲', '吸血蟲']
     ],
    multiIndex: [0, 0, 0],
   },
  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.8.3、時間選擇器

指定mode屬性為time

<view>時間選擇器</view>
<picker mode="time" value="{{time}}" start="09:01" end="21:01" bindchange="bindTimeChange">
  <view class="picker">
     目前選擇: {{time}}
  </view>
</picker>      
Page({
  data: {
    time: '12:01'
   },
  bindTimeChange: function (e) {
    console.log('picker發送選擇改變,攜帶值為', e.detail.value)
    this.setData({
      time: e.detail.value
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.8.4、日期選擇器

指定mode屬性為date

<view>日期選擇器</view>
<picker mode="date" value="{{date}}" start="2000-09-01" end="2030-09-01" bindchange="bindDateChange">
  <view class="picker">
     目前選擇: {{date}}
  </view>
</picker>      
Page({
  data: {
    date: '2030-09-01'
   },
  bindDateChange: function (e) {
    console.log('picker發送選擇改變,攜帶值為', e.detail.value)
    this.setData({
      date: e.detail.value
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.8.5、省市區選擇器

指定mode屬性為region

<view>省市區選擇器</view>
<picker mode="region" bindchange="bindRegionChange" value="{{region}}">
  <view class="picker">
     目前選擇:{{region[0]}},{{region[1]}},{{region[2]}}
  </view>
</picker>      
Page({
  data: {
    region: ['廣東省', '廣州市', '海珠區']
   },
  bindRegionChange: function (e) {
    console.log('picker發送選擇改變,攜帶值為', e.detail.value)
    this.setData({
      region: e.detail.value
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.9、slider(滑動選擇器)

使用形式

​<slider/>​

常用屬性

屬性 類型 預設值 必填 說明
step number 1 步長,取值必須大于 0,并且可被(max - min)整除
show-value boolean false 是否顯示目前 value
min number 最小值
max number 100 最大值
disabled boolean false 是否禁用
value number 目前取值
backgroundColor color #e9e9e9 背景條的顔色
activeColor color #1aad19 已選擇的顔色
block-color color #ffffff 滑塊的顔

測試代碼:

<slider />
<slider step="20"/>
<slider show-value/>
<slider min="50" max="200" show-value/>
<slider min="50" max="200" show-value disabled/>
<slider show-value value="30"/>
<slider show-value value="30" backgroundColor="red"/>
<slider show-value value="30" backgroundColor="red" activeColor="blue"/>
<slider block-color="red"/>      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.10、表單其他元件

表單是常用的元件,同樣,在表單中,也有很多配套的元件

  1. checkbox
  2. radio
  3. label
  4. switch
  5. textarea

checkbox(複選框 )

多選項目,與html複選框基本一緻

<checkboxchecked=“true”/>選中

checked 表示初始狀态為選中(true) 或 未選中(false)

配合 checkbox-group 形成一組

<checkbox-group>
  <checkbox checked="true" />讀書
  <checkbox checked="true" />打遊戲
  <checkbox />聽音樂
</checkbox-group>      

radio(單選項目)

單選項目,與html單選框基本一緻

<radiochecked=“true”/>選中

checked 表示初始狀态為選中(true) 或 未選中(false)

配合 radio-group 形成一組

<radio-group>
  <radio checked="true"/>選項1
  <radio checked="false"/>選項2
  <radio checked="false"/>選項3
  <radio checked="false"/>選項4
</radio-group>      

label(标簽)

用來改進表單元件的可用性,與html的label基本一緻

<label for="menu">
  <checkbox id="menu" checked="true"/>選中
</label>      

switch(開關選擇器)

開關選擇器,有着比較美觀的展示效果

​<switch/>​

屬性清單

屬性 類型 預設值 必填 說明
checked boolean false 是否選中
disabled boolean false 是否禁用
type string switch 樣式,有效值:switch, checkbox
color string #04BE02 switch 的顔色,同 css 的 color
<switch />
<switch checked="true"/>
<switch checked="true" disabled/>
<switch checked="true" type="checkbox"/>
<switch checked="true" color="red"/>      

textarea(多行輸入框)

多行輸入框,與html多行輸入框基本一緻

​<textarea/>​

為了可見性,我們需要增加樣式

textarea{
  border: 1px solid red;
}      
屬性 類型 預設值 必填 說明
value string 輸入框的内容
placeholder string 輸入框為空時占位符
disabled boolean false 是否禁用
maxlength number 140 最大輸入長度,設定為 -1 的時候不限制最大長度
focus boolean false 擷取焦點
auto-height boolean false 是否自動增高
<textarea value="文本内容" />
<textarea placeholder="占位符" />
<textarea maxlength="10" />
<textarea disabled />
<textarea focus />
<textarea auto-height/>      

1.11、navigator(頁面之間跳轉)

navigator 實作頁面之間的跳轉

​<navigator url="/pages/other/other">跳轉其他頁面</navigator>​

常用屬性說明

屬性 類型 預設值 必填 說明
url string 目前小程式内的跳轉連結
open-type string navigate 跳轉方式,預設打開新頁面,redirect 在目前頁面打開

測試代碼:

<navigator url="/pages/other/other" >跳轉其他頁面</navigator>
<navigator url="/pages/slider/slider" open-type="redirect">在目前頁打開</navigator>      

擴充:生命周期函數

onUnload 在之前的講解中無法測試,現在有了navigator,我們可以進行測試了

在 navigator 的屬性open-type設定為redirect時,我們可以觀察輸入結果

Page({
  onUnload() {
    console.log("解除安裝");
   }
})      

1.12、audio(音樂)

音頻播放

​<audio src="https://music.163.com/song/media/outer/url?id=1961763339" controls></audio>​

切換音樂

通過修改audio的屬性,切換音樂

<audio 
  id="{{ audioOptions.id }}"
  poster="{{ audioOptions.poster }}" 
  name="{{ audioOptions.name }}" 
  author="{{ audioOptions.author }}" 
  src="{{ audioOptions.src }}"
  controls="{{ audioOptions.controls }}"
  loop="{{ audioOptions.loop }}">
</audio>
<button type="primary" bindtap="changeMusicHandle">切換</button>      
Page({
  data: {
    audioOptions:{
      id:"myAudio",
      name:"媽媽的話",
      author:"zby忠宇",
      poster:"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg",
      src:"https://music.163.com/song/media/outer/url?id=1961763339",
      controls:true,
      loop:true
     }
   },
  changeMusicHandle(){
    this.setData({
      audioOptions:{
        id:"myAudio",
        name:"時光洪流",
        author:"程響",
        poster:"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg",
        src:"https://music.163.com/song/media/outer/url?id=1868943615",
        controls:true,
        loop:true
       }
     })
   }
})      

1.13、video(視訊)

視訊播放

<video src="http://iwenwiki.com/api/livable/livable.mp4"></video>      

為了美觀,我們将視訊寬度充滿全屏

video{
  width: 100%;
}      

屬性說明

屬性 類型 預設值 必填 說明
src string 要播放視訊的資源位址,支援網絡路徑、本地臨時路徑
duration number 指定視訊時長
controls boolean true 是否顯示預設播放控件(播放/暫停按鈕、播放進度、時間)
autoplay boolean false 是否自動播放
loop boolean false 是否循環播放
muted boolean false 是否靜音播放
initial-time number 指定視訊初始播放位置
show-mute-btn boolean false 是否顯示靜音按鈕
danmu-list Array 彈幕清單
danmu-btn boolean false 是否顯示彈幕按鈕,隻在初始化時有效,不能動态變更
enable-danmu boolean false 是否展示彈幕,隻在初始化時有效,不能動态變更

測試代碼:

<video 
  id="myVideo" src="http://iwenwiki.com/api/livable/livable.mp4"
  duration="100"
  controls
  autoplay
  loop
  muted
  initial-time="10"
  show-mute-btn
  title="制作歌曲"
  danmu-list="{{ danmuList }}"
  danmu-btn
  enable-danmu
></video>
<button type="primary" bindtap="sendDanmuHandle">發送彈幕</button>      
Page({
  data: {
    danmuList: [{
      text: '第 1s 出現的彈幕',
      color: '#ff0000',
      time: 11
     }]
   },
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
   },
  sendDanmuHandle() {
    this.videoContext.sendDanmu({
      text: "真好看",
      color: "#00ff00"
     })
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.14、camera(拍照)

系統相機。掃碼二維碼功能

<camera style="width: 100%; height: 300px;"></camera>      

屬性說明

屬性 類型 預設值 必填 說明
mode string normal 應用模式,隻在初始化時有效,不能動态變更 normal:相機模式 scanCode:掃碼模式
device-position string back 攝像頭朝向 front:前置 back:後置
flash string auto 閃光燈,值為 auto , on, off

測試代碼:

<camera mode="normal" device-position="back" flash="on" style="width: 100%; height: 300px;"></camera>
<button type="primary" bindtap="takePhotoHandle">拍照</button>
<view>預覽</view>
<image mode="widthFix" src="{{src}}"></image>屬性說明      
Page({
  data:{
    src:""
   },
  takePhotoHandle() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
         })
       }
     })
   }
})      

1.15、map(地圖)

地圖,小程式地圖實作功能相對比基礎一些,如果要實作完整的地圖能力,請參考騰訊地圖:​​https://lbs.qq.com/product/miniapp/home/​​

<map latitude="23.099994" longitude="113.324520"></map>      

屬性說明

屬性 類型 預設值 必填 說明
longitude number 中心經度
latitude number 中心緯度
scale number 16 縮放級别,取值範圍為3-20
min-scale number 3 最小縮放級别
max-scale number 20 最大縮放級别

測試代碼:

<map 
 latitude="{{latitude}}"
 longitude="{{longitude}}"
 scale="12"
 min-scale="10"
 max-scale="18"
></map>      
Page({
  data: {
    latitude: 23.099994,
    longitude: 113.324520,
   }
})      

展示效果:

從0到一開發微信小程式(4)—小程式元件

1.16、進度條(progress)

  • 進度條相信大家應該都知道是什麼吧,我們日常生活中随地可見,我這裡就不說明了

使用方式:20%的進度條

<progress percent="20"/>      

屬性設定:

屬性說明

屬性 類型 預設值 必填 說明
percent number 百分比0~100
show-info boolean false 在進度條右側顯示百分比
border-radius number/string 圓角大小
font-size number/string 16 右側百分比字型大小
stroke-width number/string 6 進度條線的寬度
activeColor string #09BB07 進度條顔色
backgroundColor string #EBEBEB 未選擇的進度條的顔色
active boolean false 進度條從左往右的動畫
duration number 30 進度增加1%

測試用例:

<progress percent="20"/>
<progress percent="20" show-info/>
<progress percent="20" show-info font-size="30"/>
<progress percent="20" show-info font-size="30" stroke-width="20"/>
<progress percent="20" border-radius="5"/>
<progress percent="20" border-radius="5" activeColor="#f00"/>
<progress percent="20" border-radius="5" activeColor="#f00" backgroundColor="#00f"/>
<progress percent="20" border-radius="5" activeColor="#f00" backgroundColor="#00f" active/>
<progress percent="20" border-radius="5" activeColor="#f00" backgroundColor="#00f" active duration="90"/>      

效果為: