Uso de componentes comunes en los miniprogramas de WeChat

Uso de componentes comunes en los miniprogramas de WeChat

Documento oficial: https://developers.weixin.qq.com/miniprogram/dev/component/

El concepto de componentes en los applets de WeChat es consistente con el de Vue (parece que los conceptos de componentes en los principales marcos principales son todos interoperables)

Aviso: Todos los nombres y atributos de los componentes están en minúsculas y varias palabras se conectarán -con guiones en inglés. Para algunos componentes de contenedores, su contenido se puede declarar entre sus etiquetas de apertura y cierre.

La siguiente tabla enumera las propiedades que tienen todos los componentes , principalmente relacionadas con los estilos y el enlace de eventos :

Nombre del Atributo tipo describir otras instrucciones
identificación Cadena ID único del componente Mantenga toda la página única
clase Cadena clase de estilo del componente Clases de estilo definidas en el WXSS correspondiente
estilo Cadena Estilos en línea para componentes Estilos en línea que se pueden configurar dinámicamente a través del enlace de datos
oculto booleano Si se muestra el componente Todos los componentes se muestran por defecto
datos-* Cualquier atributos personalizados Cuando se activa un evento en el componente, se enviará a la función del controlador de eventos
atar / atrapar Controlador de eventos evento Consulte la sección 3.5 para obtener más información.
  • Clasificación de los componentes en los applets de WeChat:

    • ver contenedor

    • contenido básico

    • componente de formulario

    • componente de navegación

    • componentes multimedia

    • componente de mapa

    • componente de lienzo

    • habilidad abierta

    • Accesibilidad

    • Barra de navegación

    • Nodo de configuración de propiedades de página

ver componente

vista

Visualización de la base de usuarios

Los componentes de la vista están expuestos inicialmente a

<view></view>

Ver descripción del atributo del componente:

Atributos tipo valores predeterminados requerido ilustrar versión mínima
clase flotante cadena ninguno No Especifica la clase de estilo prensado. En ese hover-class="none"momento , no hay efecto de estado de clic. 1.0.0
hover-stop-propagación booleano FALSO No Especifique si desea evitar que los nodos antecesores de este nodo aparezcan en el estado de clic 1.5.0
hover-start-time número 50 No ¿Cuánto tiempo aparece el estado de clic después de mantener presionado, en milisegundos? 1.0.0
hover-stay-time número 400 No Tiempo de retención del estado del clic después de soltar el dedo, en milisegundos 1.0.0

ejemplo

índice.wxtml:

<view class="container" 
hover-start-time="1500" 
hover-stay-time="1000" 
hover-class="green">
  父组件
  <view class="red size" 
  hover-class="green" 
  hover-start-time="1500" 
  hover-stay-time="1000" 
  hover-stop-propagation="{
     
     {false}}">
    View组件
  </view>
</view>

Aviso: Es necesario envolver falso y verdadero { {}}, de lo contrario, no importa si se establece en falso o verdadero, será verdadero al final (la cadena es verdadera)

índice.wxss:

/* 父组件样式 */
.container{
    
    
  background-color: grey;
}
/* 初始化样式 */
.red{
    
    
  background-color: hotpink;
  color: red;
}
.size{
    
    
  font-size: 38px;
}

/* 点击样式 */
.green{
    
    
  color: green;
}

Se muestra en rojo de forma predeterminada y se mostrará en verde durante 1 segundo después de hacer clic durante 3 segundos.

imagen-20230705093654383

imagen-20230705093745768

vista de desplazamiento

desplazamiento hecho por el usuario

<scroll-view></scroll-view>

Precauciones

  1. La altura o el ancho de los subcomponentes internos de la vista de desplazamiento deben ser más pequeños que el componente de la vista de desplazamiento, para que pueda aparecer el efecto de la barra de desplazamiento.

Propiedades comunes de los componentes de vista de desplazamiento :

Atributos tipo valores predeterminados requerido ilustrar versión mínima
desplazamiento-x booleano FALSO No Permitir desplazamiento horizontal 1.0.0
desplazamiento-y booleano FALSO No Permitir desplazamiento vertical 1.0.0
umbral superior número/cadena 50 No A qué distancia de la parte superior/izquierda se activa el evento scrolltoupper 1.0.0
umbral inferior número/cadena 50 No A qué distancia de la parte inferior/derecha se activa el evento scrolltolower 1.0.0
desplazamiento superior número/cadena No Establecer la posición de la barra de desplazamiento vertical 1.0.0
desplazarse hacia la izquierda número/cadena No Establecer la posición de la barra de desplazamiento horizontal 1.0.0
desplácese a la vista cadena No El valor debe ser una identificación de elemento secundario (la identificación no puede comenzar con un número). Establezca en qué dirección se puede desplazar, en qué dirección desplazarse hasta el elemento 1.0.0
desplazamiento con animación booleano FALSO No Use transiciones animadas al configurar la posición de la barra de desplazamiento 1.0.0
habilitar-volver-arriba booleano FALSO No Cuando iOS hace clic en la barra de estado superior y Android hace doble clic en la barra de título, la barra de desplazamiento vuelve a la parte superior, solo se admite la orientación vertical 1.0.0
habilitar-flex booleano FALSO No Habilitar el diseño de flexbox. Una vez habilitado, el nodo actual declarado display: flexse convertirá en un contenedor flexible y actuará sobre sus nodos secundarios. 2.7.3
desplazamiento-anclaje booleano FALSO No Active la función de anclaje de desplazamiento, es decir, controle la posición de desplazamiento sin sacudirse con el cambio de contenido, solo tiene efecto en iOS y consulte las overflow-anchorpropiedades de CSS en Android. 2.8.2
actualización habilitada booleano FALSO No Habilitar pull-to-refresh personalizado 2.10.1
actualización-umbral número 45 No Establecer un umbral de actualización desplegable personalizado 2.10.1
actualización-estilo predeterminado cadena "negro" No Establezca el estilo predeterminado de actualización desplegable personalizada, configuración de soporte black | white | none, ninguno significa no usar el estilo predeterminado 2.10.1
fondo de actualización cadena "#FFF" No Establecer el color de fondo del área de actualización desplegable personalizada 2.10.1
activado por actualización booleano FALSO No Establezca el estado de actualización desplegable actual, verdadero significa que se ha activado la actualización desplegable, falso significa que no se ha activado la actualización desplegable 2.10.1
mejorado booleano FALSO No Habilite la función de mejora de vista de desplazamiento, la vista de desplazamiento se puede operar a través de ScrollViewContext después de habilitar 2.12.0
rebota booleano verdadero No Control elástico de límite de vista de desplazamiento en iOS (efectivo después de habilitar la propiedad mejorada al mismo tiempo) 2.12.0
Mostrar barra de desplazamiento booleano verdadero No Barra de desplazamiento visible y control oculto (efectivo después de habilitar la propiedad mejorada al mismo tiempo) 2.12.0
paginación habilitada booleano FALSO No Efecto deslizante de paginación (efectivo después de habilitar el atributo mejorado al mismo tiempo) 2.12.0
desaceleración rápida booleano FALSO No Control de tasa de desaceleración deslizante (efectivo después de habilitar el atributo mejorado al mismo tiempo) 2.12.0
inicio vinculante manejador de eventos No Evento de inicio de deslizamiento (efectivo después de habilitar el atributo mejorado al mismo tiempo) detalle { scrollTop, scrollLeft } 2.12.0
corbata con manejador de eventos No Evento de deslizamiento (efectivo después de habilitar el atributo mejorado al mismo tiempo) detalle { scrollTop, scrollLeft } 2.12.0
binddragend eventhandle 滑动结束事件 (同时开启 enhanced 属性后生效) detail { scrollTop, scrollLeft, velocity } 2.12.0
bindscrolltoupper eventhandle 滚动到顶部/左边时触发 1.0.0
bindscrolltolower eventhandle 滚动到底部/右边时触发 1.0.0
bindscroll eventhandle 滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY} 1.0.0
bindrefresherpulling eventhandle 自定义下拉刷新控件被下拉 2.10.1
bindrefresherrefresh eventhandle 自定义下拉刷新被触发 2.10.1
bindrefresherrestore eventhandle 自定义下拉刷新被复位 2.10.1
bindrefresherabort eventhandle 自定义下拉刷新被中止 2.10.1

示例

index.wxml:

<view class="container">
    <view class="page-section">
        <view class="page-section-title">
            <text>Vertical Scroll\n纵向滚动</text>
        </view>
        <view class="page-section-spacing">
            <scroll-view class="scroll-container" 
                         scroll-y="{
     
     {true}}" 
                         bindscrolltoupper="scrolltoupper" 
                         bindscrolltolower="scrolltolower" >
                <view id="demo1" class="scroll-view-item demo-text-1">A</view>
                <view id="demo2" class="scroll-view-item demo-text-2">B</view>
                <view id="demo3" class="scroll-view-item demo-text-3">C</view>
            </scroll-view>
        </view>
    </view>
</view>

index.wxss:

.scroll-view-item{
    
    
  width: 100%;
  height: 100px;
  text-align: center;
  line-height: 100px;
  font-size: 26px;
  font-weight: bold;
} 
.demo-text-1{
    
    
  background-color: green;
}
.demo-text-2{
    
    
  background-color: red;
}
.demo-text-3{
    
    
  background-color: blue;
}
.scroll-container{
    
    
  height: 200px;
  border: 1px solid yellow;
  white-space: nowrap;
}

index.js:

Page({
    
    
  data: {
    
    

  },
  scrolltoupper:function(){
    
    
        console.log("滚动到顶部");
    },
    scrolltolower:function(){
    
    
        console.log("滚动到底部");
    }
})

imagen-20230705100547447

swiper

用户制作轮播图

<swiper></<swiper>

注意:滑块视图容器。其中只可放置swiper-item组件,否则会导致未定义的行为,我们可以使用swiper实现轮播图效果

滑块组件属性介绍:

属性 类型 默认值 必填 说明 最低版本
indicator-dots boolean false 是否显示面板指示点 1.0.0
indicator-color color rgba(0, 0, 0, .3) 指示点颜色 1.1.0
indicator-active-color color #000000 当前选中的指示点颜色 1.1.0
autoplay boolean false 是否自动切换 1.0.0
current number 0 当前所在滑块的 index 1.0.0
interval number 5000 自动切换时间间隔 1.0.0
duration number 500 滑动动画时长 1.0.0
circular boolean false 是否采用衔接滑动 1.0.0
vertical boolean false 滑动方向是否为纵向 1.0.0
previous-margin string "0px" 前边距,可用于露出前一项的一小部分,接受 px 和 rpx 值 1.9.0
next-margin string "0px" 后边距,可用于露出后一项的一小部分,接受 px 和 rpx 值 1.9.0
snap-to-edge boolean false 当 swiper-item 的个数大于等于 2,关闭 circular 并且开启 previous-margin 或 next-margin 的时候,可以指定这个边距是否应用到第一个、最后一个元素 2.12.1
display-multiple-items number 1 同时显示的滑块数量 1.9.0
easing-function string "default" 指定 swiper 切换缓动动画类型 2.6.5
合法值 说明
default 默认缓动函数
linear 线性动画
easeInCubic 缓入动画
easeOutCubic 缓出动画
easeInOutCubic 缓入缓出动画
bindchange eventhandle current 改变时会触发 change 事件,event.detail = {current, source} 1.0.0
bindtransition eventhandle swiper-item 的位置发生改变时会触发 transition 事件,event.detail = {dx: dx, dy: dy} 2.4.3
bindanimationfinish eventhandle 动画结束时会触发 animationfinish 事件,event.detail 同上 1.9.0

index.wxml:

<view class="container">
  <view class="page-body">
    <view class="page-section page-section-spacing swiper">
      <swiper indicator-dots="{
     
     {indicatorDots}}"
        autoplay="{
     
     {autoplay}}" interval="{
     
     {interval}}" duration="{
     
     {duration}}">
        <block wx:for="{
     
     {imgUrls}}" wx:key="*this">
          <swiper-item>
            <image  src="{
     
     {item}}" class="swiper-item"></image>
          </swiper-item>
        </block>
      </swiper>
    </view>
    <view class="page-section" style="margin-top: 40rpx;margin-bottom: 0;">
      <view class="weui-cells weui-cells_after-title">
        <view class="weui-cell weui-cell_switch">
          <view class="weui-cell__bd">指示点</view>
          <view class="weui-cell__ft">
            <switch checked="{
     
     {indicatorDots}}" bindchange="changeIndicatorDots" />
          </view>
        </view>
        <view class="weui-cell weui-cell_switch">
          <view class="weui-cell__bd">自动播放</view>
          <view class="weui-cell__ft">
            <switch checked="{
     
     {autoplay}}" bindchange="changeAutoplay" />
          </view>
        </view>
      </view>
    </view>

    <view class="page-section page-section-spacing">
      <view class="page-section-title">
        <text>幻灯片切换时长{
   
   {duration}}(ms)</text>
      </view>
      <slider bindchange="durationChange" value="{
     
     {duration}}" min="500" max="2000"/>
      <view class="page-section-title">
        <text>自动播放间隔时长{
   
   {interval}}(ms)</text>
      </view>
      <slider bindchange="intervalChange" value="{
     
     {interval}}" min="2000" max="10000"/>
    </view>
  </view>
</view>

index.wxsss:

page {
    
    
  background-color: #F8F8F8;
  height: 100%;
  font-size: 32rpx;
  line-height: 1.6;
}

.page-body {
    
    
  padding-top: 60rpx;
}

.page-section {
    
    
  width: 100%;
  margin-bottom: 60rpx;
}

.page-section_center {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
}

.page-section:last-child {
    
    
  margin-bottom: 0;
}

.page-section-gap {
    
    
  box-sizing: border-box;
  padding: 0 30rpx;
}

.page-section-spacing {
    
    
  box-sizing: border-box;
  padding: 0 80rpx;
}

.page-section-title {
    
    
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 10rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
}

.page-section-gap .page-section-title {
    
    
  padding-left: 0;
  padding-right: 0;
}

button {
    
    
  margin-bottom: 30rpx;
}

button:last-child {
    
    
  margin-bottom: 0;
}

.page-section-title {
    
    
  padding: 0;
}

.swiper-item {
    
    
  display: block;
  height: 150px;
}

.page-section-title {
    
    
  margin-top: 60rpx;
  position: relative;
}

.weui-cells {
    
    
  position: relative;
  margin-top: 1.17647059em;
  background-color: #FFFFFF;
  line-height: 1.41176471;
  font-size: 17px;
}

.weui-cells_after-title {
    
    
  margin-top: 0;
}

.weui-cell {
    
    
  padding: 10px 15px;
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.weui-cell_switch {
    
    
  padding-top: 6px;
  padding-bottom: 6px;
}

.weui-cell__bd {
    
    
  flex: 1;
}

.weui-cell__ft {
    
    
  text-align: right;
  color: #999999;
}

index.js:

Page({
    
    
  data: {
    
    
      imgUrls: ['./images/1.jpg', './images/2.jpg', './images/3.jpg'],
      indicatorDots: true,
      vertical: false,
      autoplay: false,
      circular: false,
      interval: 2000,
      duration: 500,
      previousMargin: 0,
      nextMargin: 0
    },
    changeProperty: function (e) {
    
    
      var propertyName = e.currentTarget.dataset.propertyName
      var newData = {
    
    }
      newData[propertyName] = e.detail.value
      this.setData(newData)
    },
    changeIndicatorDots: function (e) {
    
    
      this.setData({
    
    
        indicatorDots: !this.data.indicatorDots
      })
    },
    changeAutoplay: function (e) {
    
    
      this.setData({
    
    
        autoplay: !this.data.autoplay
      })
    },
    intervalChange: function (e) {
    
    
      this.setData({
    
    
        interval: e.detail.value
      })
    },
    durationChange: function (e) {
    
    
      this.setData({
    
    
        duration: e.detail.value
      })
    }
  })

imagen-20230705102144162

movable-area

用户设置组件拖动的方式

movable-area组件属性说明

属性 类型 默认值 必填 说明 最低版本
scale-area Boolean false 当里面的 movable-view 设置为支持双指缩放时,设置此值可将缩放手势生效区域修改为整个movable-area 1.9.90

注意事项

  1. movable-area 必须设置 width 和height属性,不设置默认为10px
  2. 当 movable-view 小于 movable-area 时,movable-view的移动范围是在 movable-area 内
  3. 当 movable-view 大于 movable-area 时,movable-view的移动范围必须包含movable-area(x轴方向和 y 轴方向分开考虑)
  4. movable-view必须在 movable-area 组件中,并且必须是直接子节点,否则不能移动
  5. movable-view 必须设置 width 和height属性,不设置默认为10px
  6. movable-view 默认为绝对定位,top和 left 属性为0px

movable-view组件属性说明

属性 类型 默认值 必填 说明 最低版本
direction string none movable-view的移动方向,属性值有all、vertical、horizontal、none 1.2.0
inertia boolean false movable-view是否带有惯性 1.2.0
out-of-bounds boolean false 超过可移动区域后,movable-view是否还可以移动 1.2.0
x number/string 定义 x 轴方向的偏移,如果 x 的值不在可移动范围内,会自动移动到可移动范围;改变 x 的值会触发动画;单位支持px(默认)、rpx; 1.2.0
y number/string 定义 y 轴方向的偏移,如果 y 的值不在可移动范围内,会自动移动到可移动范围;改变 y 的值会触发动画;单位支持px(默认)、rpx; 1.2.0
damping number 20 阻尼系数,用于控制 x 或y改变时的动画和过界回弹的动画,值越大移动越快 1.2.0
friction number 2 摩擦系数,用于控制惯性滑动的动画,值越大摩擦力越大,滑动越快停止;必须大于0,否则会被设置成默认值 1.2.0
disabled boolean false 是否禁用 1.9.90
scale boolean false 是否支持双指缩放,默认缩放手势生效区域是在 movable-view 内 1.9.90
scale-min number 0.5 定义缩放倍数最小值 1.9.90
scale-max number 10 定义缩放倍数最大值 1.9.90
scale-value number 1 定义缩放倍数,取值范围为 0.5 - 10 1.9.90
animation boolean true 是否使用动画 2.1.0
bindchange eventhandle 拖动过程中触发的事件,event.detail = {x, y, source} 1.9.90
bindscale eventhandle 缩放过程中触发的事件,event.detail = {x, y, scale},x和 y 字段在2.1.0之后支持 1.9.90
htouchmove eventhandle 初次手指触摸后移动为横向的移动时触发,如果 catch 此事件,则意味着 touchmove 事件也被catch 1.9.90
vtouchmove eventhandle 初次手指触摸后移动为纵向的移动时触发,如果 catch 此事件,则意味着 touchmove 事件也被catch 1.9.90

index.wxml:

<movable-area class="container1">
  <movable-view class="size" direction="all">A</movable-view>
</movable-area>

index.wxss:

.container1{
    
    
    width: 100%;
    height: 500px;
    background-color: grey;
}

.size{
    
    
    width:100px;
    height: 100px;
    background-color: lawngreen;
    text-align: center;
    font-size: 26px;
    line-height: 100px;
}

imagen-20230705103150635

基础组件

名称 功能说明
icon 图标组件
progress 进度条
rich-text 富文本
text 文本

icon

<icon></<icon>

属性说明:

属性 类型 默认值 必填 说明 最低版本
type string icon的类型,有效值:success, success_no_circle, info, warn, waiting, cancel, download, search, clear 1.0.0
size number/string 23 icon的大小,单位默认为px,2.4.0起支持传入单位(rpx/px),2.21.3起支持传入其余单位(rem 等)。 1.0.0
color string icon的颜色,同 css 的color 1.0.0
<icon type="success" size="60" color="blue"></icon>

imagen-20230705104956529

text

文本组件,用于显示文本

 <text></text>

注意事项

  1. 该组件支持转义符
  2. text标签不可以嵌套别的组件,但是可以嵌套自己
  3. 如果需要长按选中文本的话,必须使用text标签包裹

属性说明:

属性 类型 默认值 必填 说明 最低版本
selectable boolean false 文本是否可选 (已废弃) 1.1.0
user-select boolean false 文本是否可选,该属性会使文本节点显示为 inline-block 2.12.1
space string 显示连续空格 1.4.0
合法值 说明
ensp 中文字符空格一半大小
emsp 中文字符空格大小
nbsp 根据字体设置的空格大小
decode boolean false 是否解码 1.4.0
<text decode="{
     
     {true}}">
     你好,        世界 &gt; &lt; &nbsp;   
</text>

imagen-20230705103934175

imagen-20230705104107314

rich-text

富文本组件

<rich-text></rich-text>

注意事项

  1. nodes 不推荐使用 String 类型,性能会有所下降。
  2. rich-text 组件内屏蔽所有节点的事件。
  3. attrs 属性不支持 id ,支持 class 。
  4. name 属性大小写不敏感。
  5. 如果使用了不受信任的 HTML 节点,该节点及其所有子节点将会被移除。
  6. img 标签仅支持网络图片。
  7. 如果在自定义组件中使用 rich-text 组件,那么仅自定义组件的 wxss 样式对 rich-text 中的 class 生效。

rich-text组件属性说明:

属性 类型 默认值 必填 说明 最低版本
nodes array/string [] 节点列表/HTML String 1.4.0
space string 显示连续空格 2.4.1
合法值 说明
ensp 中文字符空格一半大小
emsp 中文字符空格大小
nbsp 根据字体设置的空格大小
user-select boolean false 文本是否可选,该属性会使节点显示为 block 2.24.0

元素节点:type = node

属性 说明 类型 必填 备注
name 标签名 string 支持部分受信任的 HTML 节点
attrs 属性 object 支持部分受信任的属性,遵循 Pascal 命名法
children 子节点列表 array 结构和 nodes 一致

文本节点:type = text

属性 说明 类型 必填 备注
text 文本 string 支持entities

示例

<view class="container">
  <rich-text nodes="{
     
     {htmlSnip}}"></rich-text>
  <hr/>
  <rich-text nodes="{
     
     {arraySnip}}"></rich-text>
</view>
const htmlSnip =`<div class="div_class">
                    <h1>Title</h1>
                    <p class="p">
                    Life is&nbsp;<i>like</i>&nbsp;a box of
                    <b>&nbsp;chocolates</b>.
                    </p>
                </div>`;
Page({
    
    

    /**
     * 页面的初始数据
     */
    data: {
    
    
        htmlSnip:htmlSnip,
        arraySnip:[{
    
    
            name: 'div',
            attrs: {
    
    
              class: 'div_class',
              style: 'line-height: 60px; color: #1AAD19;'
            },
            children: [{
    
    
              type: 'text',
              text: 'You never know what you\'re gonna get.'
            }]
          }]
    }
})

imagen-20230705104707192

progress

进程组件

<progress></progress>

属性说明:

属性 类型 默认值 必填 说明 最低版本
percent number 百分比0~100 1.0.0
show-info boolean false 在进度条右侧显示百分比 1.0.0
border-radius number/string 0 圆角大小 2.3.1
font-size number/string 16 右侧百分比字体大小 2.3.1
stroke-width number/string 6 进度条线的宽度 1.0.0
color string #09BB07 进度条颜色(请使用activeColor) 1.0.0
activeColor string #09BB07 已选择的进度条的颜色 1.0.0
backgroundColor string #EBEBEB 未选择的进度条的颜色 1.0.0
active boolean false 进度条从左往右的动画 1.0.0
active-mode string backwards backwards: 动画从头播;forwards:动画从上次结束点接着播 1.7.0
duration number 30 进度增加1%所需毫秒数 2.8.2
bindactiveend eventhandle 动画完成事件 2.4.1

示例

<text>20%</text>
<view class="progress-box">
  <progress percent="20" show-info stroke-width="3"/>
</view>

<text>40%</text>

<view class="progress-box">
  <progress percent="40" active stroke-width="3" />
</view>

<text>60%</text>

<view class="progress-box">
  <progress percent="60" active stroke-width="3" />
</view>

<text>80%</text>

<view class="progress-box">
  <progress percent="80" color="#10AEFF" active stroke-width="3" />
</view>

imagen-20230705110440022

表单组件

名称 功能说明
button 按钮
checkbox 多选项目
checkbox-group 多项选择器,内部由多个checkbox组成
editor 富文本编辑器,可以对图片、文字进行编辑。
form 表单。将组件内的用户输入的switch input checkbox slider radio picker 提交
input 输入框
keyboard-accessory 设置 input / textarea 聚焦时键盘上方 cover-view / cover-image 工具栏视图
label 用来改进表单组件的可用性
picker 从底部弹起的滚动选择器
picker-view 组件中,宽高自嵌入页面的滚动选择器。其中只可放置 picker-view-column组件,其它节点不会显示
picker-view-column 滚动选择器子项。仅可放置于picker-view中,其孩子节点的高度会自动设置成与picker-view的选中框的高度一致
radio 单选项目
radio-group 单项选择器,内部由多个 radio 组成
slider 滑动选择器
switch 开关选择器
textarea 多行输入框

button

按钮组件

<button size="mini" type="primary" 	loading="true">按钮</button>
<button size="mini"  type="warn" disabled="true" >按钮2</button>
<button size="mini" plain="true" type="warn" >按钮3</button>

注意事项

  1. button-hover 默认为{background-color: rgba(0, 0, 0, 0.1); opacity: 0.7;}
  2. bindgetphonenumber 从1.2.0 开始支持,但是在1.5.3以下版本中无法使用wx.canIUse进行检测,建议使用基础库版本进行判断。
  3. bindgetphonenumber 等返回加密信息的回调中调用 wx.login 登录,可能会刷新登录态。此时服务器使用 code 换取的 sessionKey 不是加密时使用的 sessionKey,导致解密失败。建议开发者提前进行 login;或者在回调中先使用 checkSession 进行登录态检查,避免 login 刷新登录态。
  4. 从 2.21.2 起,对getPhoneNumber接口进行了安全升级,bindgetphonenumber 返回的信息中增加code参数,code是一个动态的令牌,开发者拿到code后需调用微信后台接口换取手机号。详情新版接口使用指南
  5. 从 2.1.0 起,button 可作为原生组件的子节点嵌入,以便在原生组件上使用 open-type 的能力。
  6. 目前设置了 form-typebutton 只会对当前组件中的 form 有效。因而,将 button 封装在自定义组件中,而 form 在自定义组件外,将会使这个 buttonform-type 失效

属性说明:

属性 类型 默认值 必填 说明 最低版本
size string default 按钮的大小 1.0.0
合法值 说明
default 默认大小
mini 小尺寸
type string default 按钮的样式类型 1.0.0
合法值 说明
primary 绿色
default 白色
warn 红色
plain boolean false 按钮是否镂空,背景色透明 1.0.0
disabled boolean false 是否禁用 1.0.0
loading boolean false 名称前是否带 loading 图标 1.0.0
form-type string 用于 form 组件,点击分别会触发 form 组件的 submit/reset 事件 1.0.0
合法值 说明
submit 提交表单
reset 重置表单
open-type string 微信开放能力 1.1.0
合法值 说明 最低版本
contact 打开客服会话,如果用户在会话中点击消息卡片后返回小程序,可以从 bindcontact 回调中获得具体信息,具体说明 (*小程序插件中不能使用*) 1.1.0
share 触发用户转发,使用前建议先阅读使用指引 1.2.0
getPhoneNumber 获取用户手机号,可以从 bindgetphonenumber 回调中获取到用户信息,具体说明 (*小程序插件中不能使用*) 1.2.0
getUserInfo 获取用户信息,可以从 bindgetuserinfo 回调中获取到用户信息 (*小程序插件中不能使用*) 1.3.0
launchApp 打开APP,可以通过 app-parameter 属性设定向 APP 传的参数具体说明 1.9.5
openSetting 打开授权设置页 2.0.7
feedback 打开“意见反馈”页面,用户可提交反馈内容并上传日志,开发者可以登录小程序管理后台后进入左侧菜单“客服反馈”页面获取到反馈内容 2.1.0
chooseAvatar 获取用户头像,可以从 bindchooseavatar 回调中获取到头像信息 2.21.2
hover-class string button-hover 指定按钮按下去的样式类。当 hover-class="none" 时,没有点击态效果 1.0.0
hover-stop-propagation boolean false 指定是否阻止本节点的祖先节点出现点击态 1.5.0
hover-start-time number 20 按住后多久出现点击态,单位毫秒 1.0.0
hover-stay-time number 70 手指松开后点击态保留时间,单位毫秒 1.0.0
lang string en 指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文。 1.3.0
合法值 说明
en 英文
zh_CN 简体中文
zh_TW 繁体中文
session-from string 会话来源,open-type="contact"时有效 1.4.0
send-message-title string 当前标题 会话内消息卡片标题,open-type="contact"时有效 1.5.0
send-message-path string 当前分享路径 会话内消息卡片点击跳转小程序路径,open-type="contact"时有效 1.5.0
send-message-img string 截图 会话内消息卡片图片,open-type="contact"时有效 1.5.0
app-parameter string 打开 APP 时,向 APP 传递的参数,open-type=launchApp时有效 1.9.5
show-message-card boolean false 是否显示会话内消息卡片,设置此参数为 true,用户进入客服会话会在右下角显示"可能要发送的小程序"提示,用户点击后可以快速发送小程序消息,open-type="contact"时有效 1.5.0
bindgetuserinfo eventhandle 用户点击该按钮时,会返回获取到的用户信息,回调的 detail 数据与wx.getUserInfo返回的一致,open-type="getUserInfo"时有效 1.3.0
bindcontact eventhandle 客服消息回调,open-type="contact"时有效 1.5.0
bindgetphonenumber eventhandle 获取用户手机号回调,open-type=getPhoneNumber时有效 1.2.0
binderror eventhandle 当使用开放能力时,发生错误的回调,open-type=launchApp时有效 1.9.5
bindopensetting eventhandle 在打开授权设置页后回调,open-type=openSetting时有效 2.0.7
bindlaunchapp eventhandle 打开 APP 成功的回调,open-type=launchApp时有效 2.4.4
bindchooseavatar eventhandle 获取用户头像回调,open-type=chooseAvatar时有效 2.21.2

checkbox、checkbox-group

   <checkbox-group bindchange="chooseLove">
        <checkbox value="read" checked="true"/>
    </checkbox-group>

注意事项:同一组的checkbox需要用一个checkbox-group包裹

checkbox-group属性说明 :

属性 类型 默认值 必填 说明 最低版本
bindchange EventHandle checkbox-group中选中项发生改变时触发 change 事件,detail = {value:[选中的 checkbox 的value的数组]} 1.0.0

checkbox属性说明:

属性 类型 默认值 必填 说明 最低版本
value string checkbox标识,选中时触发checkbox-group的 change 事件,并携带 checkbox 的 value 1.0.0
disabled boolean false 是否禁用 1.0.0
checked boolean false 当前是否选中,可用来设置默认选中 1.0.0
color string #09BB07 checkbox的颜色,同 css 的color 1.0.0
<view>
   爱好: 
   <checkbox-group bindchange="chooseLove">
        <checkbox value="read" checked="true"/> 阅读
        <checkbox value="sport"/> 运动
        <checkbox value="music" /> 音乐 
    </checkbox-group>
</view>
<view>
    <text>循环生成checkbox</text>
   <checkbox-group>
        <view  wx:for="{
     
     {provinces}}" wx:key="*this">
            <checkbox value="{
     
     {item.py}}" />{
   
   {item.text}}
        </view>
    </checkbox-group>
</view>
Page({
    
    
    data:{
    
    
         provinces:[
               {
    
    py:'hunan',text:'湖南'},
               {
    
    py:'guangdong',text:'广东'},
               {
    
    py:'shanghai',text:'上海'},
               {
    
    py:'hubei',text:'湖北'},
              ]
    },
    chooseLove:function(e){
    
    
            //通过事件对象的detail.value获取选中的checkbox的value
            console.log(e.detail.value)
     }
})

imagen-20230706091921008

label

我们可以使用label包裹文本,与对应的表单组件进行管理, 从而当我们点击文本的时候,也可以操作对应绑定的组件, label使用for管理对应组件的id,目前可以绑定的控件有:button, checkbox, radio, switch, input

属性说明:

属性 类型 默认值 必填 说明 最低版本
for string 绑定控件的 id 1.0.0

​ 我们上面的checkbox案例,当我们点击文本的时候,不会对我们的checkbox框进行操作, 这样不是很友好,那我们可以把文本使用label包裹, 并使用for关联对应的checkbox,这样我们就可以实现上面的效果了.

<view>
    <text>循环生成checkbox</text>
   <checkbox-group>
        <view  wx:for="{
     
     {provinces}}" wx:key="*this">
            <checkbox value="{
     
     {item.py}}" id="{
     
     {item.py}}" /> 
            <label for="{
     
     {item.py}}">{
   
   {item.text}}</label>
        </view>
    </checkbox-group>
</view>
Page({
    
    
  data:{
    
    
    provinces:[
      {
    
    py:'hunan',text:'湖南'},
      {
    
    py:'guangdong',text:'广东'},
      {
    
    py:'shanghai',text:'上海'},
      {
    
    py:'hubei',text:'湖北'},
     ]
  },
  chooseLove:function(e){
    
    
          //通过事件对象的detail.value获取选中的checkbox的value
          console.log(e.detail.value)
   }
})

imagen-20230710163019888

form

表单。将组件内的用户输入的switch input checkbox slider radio picker 提交。

当点击 form 表单中 form-type 为 submit 的 button 组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。

<form></form>

表单组件属性说明


属性 类型 默认值 必填 说明 最低版本
report-submit boolean false 是否返回 formId 用于发送模板消息 1.0.0
report-submit-timeout number 0 等待一段时间(毫秒数)以确认 formId 是否生效。如果未指定这个参数,formId 有很小的概率是无效的(如遇到网络失败的情况)。指定这个参数将可以检测 formId 是否有效,以这个参数的时间作为这项检测的超时时间。如果失败,将返回 requestFormId:fail 开头的 formId 2.6.2
bindsubmit eventhandle 携带 form 中的数据触发 submit 事件,event.detail = {value : {'name': 'value'} , formId: ''} 1.0.0
bindreset eventhandle 表单重置时会触发 reset 事件 1.0.0
<form bindsubmit="submitForm">
    <view>
    爱好: 
    <checkbox-group bindchange="chooseLove" name="love">
            <checkbox value="read" checked="true"/> 阅读
            <checkbox value="sport"/> 运动
            <checkbox value="music" /> 音乐 
        </checkbox-group>
    </view>

    <view>
        <text>循环生成checkbox</text>
        <checkbox-group name="province">
            <view  wx:for="{
     
     {provinces}}" wx:key="*this">
                <checkbox value="{
     
     {item.py}}" id="{
     
     {item.py}}" /> <label for="{
     
     {item.py}}">{
   
   {item.text}}</label>
            </view>
        </checkbox-group>
    </view>
    <button form-type="submit" type="primary">提交</button>
    <button form-type="reset" type="warn">重置</button>
</form>
Page({
    
    
  data: {
    
    
      provinces:[
             {
    
    py:'hunan',text:'湖南'},
             {
    
    py:'guangdong',text:'广东'},
             {
    
    py:'shanghai',text:'上海'},
             {
    
    py:'hubei',text:'湖北'},
            ]

  },
  // 选中爱好触发事件
  chooseLove:function(e){
    
    
    // 打印选中的爱好
      console.log(e.detail.value)
  },
  // 提交表单触发
  submitForm:function(e){
    
    
    // 打印选中的checkbox
    console.log(e.detail.value)
  }
})

imagen-20230706092747298

input

输入框组件,用户表单数据的输入

<intpu></intpu>
  1. confirm-type的最终表现与手机输入法本身的实现有关,部分安卓系统输入法和第三方输入法可能不支持或不完全支持
  2. input 组件是一个原生组件,字体是系统字体,所以无法设置 font-family
  3. 在 input 聚焦期间,避免使用 css 动画
  4. 对于将 input 封装在自定义组件中、而 form 在自定义组件外的情况, form 将不能获得这个自定义组件中 input 的值。此时需要使用自定义组件的 内置 behaviors wx://form-field
  5. 键盘高度发生变化,keyboardheightchange事件可能会多次触发,开发者对于相同的 height 值应该忽略掉

input属性说明:

属性 类型 默认值 必填 说明 最低版本
value string 输入框的初始内容 1.0.0
type string text input 的类型 1.0.0
合法值 说明 最低版本
text 文本输入键盘
number 数字输入键盘
idcard 身份证输入键盘
digit 带小数点的数字键盘
safe-password 密码安全输入键盘 指引 2.18.0
nickname 昵称输入键盘 2.21.2
password boolean false 是否是密码类型 1.0.0
placeholder string 输入框为空时占位符 1.0.0
placeholder-style string 指定 placeholder 的样式 1.0.0
placeholder-class string input-placeholder 指定 placeholder 的样式类 1.0.0
disabled boolean false 是否禁用 1.0.0
maxlength number 140 最大输入长度,设置为 -1 的时候不限制最大长度 1.0.0
cursor-spacing number 0 指定光标与键盘的距离,取 input 距离底部的距离和 cursor-spacing 指定的距离的最小值作为光标与键盘的距离 1.0.0
auto-focus boolean false (即将废弃,请直接使用 focus )自动聚焦,拉起键盘 1.0.0
focus boolean false 获取焦点 1.0.0
confirm-type string done 设置键盘右下角按钮的文字,仅在type='text'时生效 1.1.0
合法值 说明
send 右下角按钮为“发送”
search 右下角按钮为“搜索”
next 右下角按钮为“下一个”
go 右下角按钮为“前往”
done 右下角按钮为“完成”
always-embed boolean false 强制 input 处于同层状态,默认 focus 时 input 会切到非同层状态 (仅在 iOS 下生效) 2.10.4
confirm-hold boolean false 点击键盘右下角按钮时是否保持键盘不收起 1.1.0
cursor number 指定 focus 时的光标位置 1.5.0
selection-start number -1 光标起始位置,自动聚集时有效,需与 selection-end 搭配使用 1.9.0
selection-end number -1 光标结束位置,自动聚集时有效,需与 selection-start 搭配使用 1.9.0
adjust-position boolean true 键盘弹起时,是否自动上推页面 1.9.90
hold-keyboard boolean false focus时,点击页面的时候不收起键盘 2.8.2
safe-password-cert-path string 安全键盘加密公钥的路径,只支持包内路径 2.18.0
safe-password-length number 安全键盘输入密码长度 2.18.0
safe-password-time-stamp number 安全键盘加密时间戳 2.18.0
safe-password-nonce string 安全键盘加密盐值 2.18.0
safe-password-salt string 安全键盘计算 hash 盐值,若指定custom-hash 则无效 2.18.0
safe-password-custom-hash string 安全键盘计算 hash 的算法表达式,如 md5(sha1('foo' + sha256(sm3(password + 'bar')))) 2.18.0
bindinput eventhandle 键盘输入时触发,event.detail = {value, cursor, keyCode},keyCode 为键值,2.1.0 起支持,处理函数可以直接 return 一个字符串,将替换输入框的内容。 1.0.0
bindfocus eventhandle 输入框聚焦时触发,event.detail = { value, height },height 为键盘高度,在基础库 1.9.90 起支持 1.0.0
bindblur eventhandle 输入框失去焦点时触发,event.detail = { value, encryptedValue, encryptError } 1.0.0
bindconfirm eventhandle 点击完成按钮时触发,event.detail = { value } 1.0.0
bindkeyboardheightchange eventhandle 键盘高度发生变化的时候触发此事件,event.detail = {height: height, duration: duration} 2.7.0
<view class="page-body">
  <view class="page-section">
    <view class="weui-cells__title">可以自动聚焦的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" focus="{
     
     {focus}}" placeholder="将会获取焦点"/>
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">控制最大输入长度的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" maxlength="10" placeholder="最大输入长度为10" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">实时获取输入值:{
   
   {inputValue}}</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input"  maxlength="10" bindinput="bindKeyInput" placeholder="输入同步到view中"/>
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">控制输入的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input"  bindinput="bindReplaceInput" placeholder="连续的两个1会变成2" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">控制键盘的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input"  bindinput="bindHideKeyboard" placeholder="输入123自动收起键盘" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">数字输入的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" type="number" placeholder="这是一个数字输入框" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">密码输入的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" password type="text" placeholder="这是一个密码输入框" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">带小数点的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" type="digit" placeholder="带小数点的数字键盘"/>
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">身份证输入的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" type="idcard" placeholder="身份证输入键盘" />
      </view>
    </view>
  </view>
  <view class="page-section">
    <view class="weui-cells__title">控制占位符颜色的input</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" placeholder-style="color:#F76260" placeholder="占位符字体是红色的" />
      </view>
    </view>
  </view>
</view>
Page({
    
    
  data: {
    
    
    focus: false,
    inputValue: ''
  },
  bindKeyInput: function (e) {
    
    
    this.setData({
    
    
      inputValue: e.detail.value
    })
  },
  // 连续输入两个1,会编程一个2
  bindReplaceInput: function (e) {
    
    
    console.log(e.detail)
    // 获取当前输入框的值
    var value = e.detail.value
    // 获取当前光标的位置
    console.log(e.detail)
    var pos = e.detail.cursor
    return {
    
    
      value: value.replace(/11/g, '2'),
      cursor: pos
    }
  },
  // 用户输入123,触发事件
  bindHideKeyboard: function (e) {
    
    
    if (e.detail.value === '123') {
    
    
      // 收起键盘
      wx.hideKeyboard()
    }
  }
})

imagen-20230706100932733

picker

从底部弹起的滚动选择器

<picker></picker>

picker组件属性说明:

属性 类型 默认值 必填 说明 最低版本
header-text string 选择器的标题,仅安卓可用 2.11.0
mode string selector 选择器类型 1.0.0
合法值 说明
selector 普通选择器
multiSelector 多列选择器
time 时间选择器
date 日期选择器
region 省市区选择器
disabled boolean false 是否禁用 1.0.0
bindcancel eventhandle 取消选择时触发 1.9.90

除了上述通用的属性,对于不同的mode,picker拥有不同的属性。

单列选择器

普通选择器:mode = selector

普通选择器常用属性

属性名 类型 默认值 说明 最低版本
range array/object array [] mode 为 selector 或 multiSelector 时,range 有效
range-key string 当 range 是一个 Object Array 时,通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
value number 0 表示选择了 range 中的第几个(下标从 0 开始)
bindchange eventhandle value 改变时触发 change 事件,event.detail = {value}
<view>
    <picker bindchange="bindPickerChange" value="{
     
     {index}}" range="{
     
     {array}}">
        <view>
            请选择序号:{
   
   {array[index]}}
        </view>
    </picker>
</view>

<view>
    <picker bindchange="bindPickerChange2" value="{
     
     {index}}" range="{
     
     {objectArray}}"range-key="name">
        <view>
            当前选择的姓名:{
   
   {name}}
        </view>
    </picker>
</view>
Page({
    
    
  data: {
    
    
      array:[1,2,3,4,5],
      index:-1,
      objectArray:[
          {
    
    id:1,name:'张三'},
          {
    
    id:2,name:'李四'},
          {
    
    id:3,name:'王五'},
          {
    
    id:4,name:'赵六'}
      ],
      name:'请选择人名',
  },

  bindPickerChange:function(e){
    
    
      //获取选中的下标
      var index = e.detail.value;
      //设置data中的index
      this.setData({
    
    
          index:index,
      });
  },
  bindPickerChange2:function(e){
    
    
      var index = e.detail.value;
       //设置data中的index
       this.setData({
    
    
          name:this.data.objectArray[index].name,
      });
  }
})

imagen-20230710163104060

多列选择器

多列选择器:mode = multiSelector,与普通选择器的区别在于,多列选择器要求数组必须是一个二维的数组

属性名 类型 默认值 说明 最低版本
range array/object array [] mode 为 selector 或 multiSelector 时,range 有效
range-key string 当 range 是一个 Object Array 时,通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
value array [] 表示选择了 range 中的第几个(下标从 0 开始)
bindchange eventhandle value改变时触发change事件,event.detail= {value: value}
bindcolumnchange eventhandle 某一列的值改变时触发columnchange事件,event.detail = {column: column, value:value} , column的值表示改变了第几列(下标从0开始) , value 的值表示变更值的下标
<view>
    <view>多列选择器</view>
    <picker bindchange="bindPickerChange" value="{
     
     {index}}" range="{
     
     {array}}" mode="multiSelector">
        <view>
            当前选择:{
   
   {num}}
        </view>
    </picker>
</view>

<view>
    <view>多列选择器2</view>
    <picker bindchange="bindPickerChange2" value="{
     
     {index}}" range="{
     
     {objectArray}}" range-key="name" mode="multiSelector">
        <view>
            当前选择:{
   
   {name}}
        </view>
    </picker>
</view>
Page({
    
    
    data: {
    
    
        array:[[1,2,3,4,5],[6,7,8,9,10]],
        num:"",
        objectArray:[
            [
                {
    
    id:1,name:'张三'},
                {
    
    id:2,name:'李四'},
                {
    
    id:3,name:'王五'},
                {
    
    id:4,name:'赵六'}
            ],
            [
                {
    
    id:1,name:'张三'},
                {
    
    id:2,name:'李四'},
                {
    
    id:3,name:'王五'},
                {
    
    id:4,name:'赵六'}
            ]
        ],
        name:'请选择人名',
    },

    bindPickerChange:function(e){
    
    
        //获取选中的下标
        var indexs = e.detail.value;
        //设置data中的index
        this.setData({
    
    
            num:this.data.array[0][indexs[0]]+'-->'+this.data.array[1][indexs[1]],
        });
    },
    bindPickerChange2:function(e){
    
    
        var indexs = e.detail.value;
         //设置data中的index
         this.setData({
    
    
            name:this.data.objectArray[0][indexs[0]].name +'-->'+this.data.objectArray[1][indexs[1]].name,
        });
    }
})

imagen-20230710163135270

时间选择器&日期选择器&地区选择器

时间选择器:mode = time

时间选择器常见属性

属性名 类型 默认值 说明 最低版本
value string 表示选中的时间,格式为"hh:mm"
start string 表示有效时间范围的开始,字符串格式为"hh:mm"
end string 表示有效时间范围的结束,字符串格式为"hh:mm"
bindchange eventhandle value 改变时触发 change 事件,event.detail = {value}

日期选择器:mode = date

日期选择器常见属性

属性名 类型 默认值 说明 最低版本
value string 当天 表示选中的日期,格式为"YYYY-MM-DD"
start string 表示有效日期范围的开始,字符串格式为"YYYY-MM-DD"
end string 表示有效日期范围的结束,字符串格式为"YYYY-MM-DD"
fields string day 有效值 year,month,day,表示选择器的粒度
bindchange eventhandle value 改变时触发 change 事件,event.detail = {value}

fields 有效值:

说明
year 选择器粒度为年
month 选择器粒度为月份
day 选择器粒度为天

省市区选择器:mode = region

地区选择器常见属性

属性名 类型 默认值 说明 最低版本
value array [] 表示选中的省市区,默认选中每一列的第一个值
custom-item string 可为每一列的顶部添加一个自定义的项 1.5.0
level string region 选择器层级 2.21.1
bindchange eventhandle value 改变时触发 change 事件,event.detail = {value, code, postcode},其中字段 code 是统计用区划代码,postcode 是邮政编码

level 的有效值

说明
province 省级选择器
city 市级选择器
region 区级选择器
sub-district 街道选择器
<view>
  <view >时间选择器</view>
  <picker mode="time" value="{
     
     {time}}" start="09:01" end="21:01" bindchange="bindTimeChange">
    <view class="picker">
      当前选择: {
   
   {time}}
    </view>
  </picker>
</view>

<view>
  <view>日期选择器</view>
  <picker mode="date" value="{
     
     {date}}" start="2015-09-01" end="2017-09-01" bindchange="bindDateChange">
    <view class="picker">
      当前选择: {
   
   {date}}
    </view>
  </picker>
</view>

<view>
  <view>省市区选择器</view>
  <picker mode="region" bindchange="bindRegionChange"  custom-item="{
     
     {customItem}}">
    <view class="picker">
      当前选择:{
   
   {region}}
    </view>
  </picker>
</view>
// pages/picker/picker.js
Page({
    
    
    data: {
    
    
       time:'请选择时间',
       date:'请选择日期',
       customItem:'全部',
       region:'',
    },

    bindTimeChange:function(e){
    
    
        //获取选中的下标
        //设置data中的index
        this.setData({
    
    
            time:e.detail.value,
        });
    },
    bindDateChange:function(e){
    
    
        this.setData({
    
    
            date:e.detail.value,
        });
    },
    bindRegionChange:function(e){
    
    
        console.log(e.detail.value);
        this.setData({
    
    
            region:e.detail.value,
        });
    }
   
})

imagen-20230706101102500

picker-view

嵌入页面的滚动选择器。其中只可放置 picker-view-column组件

属性说明:

属性 类型 默认值 必填 说明 最低版本
value Array.<number> 数组中的数字依次表示 picker-view 内的 picker-view-column 选择的第几项(下标从 0 开始),数字大于 picker-view-column 可选项长度时,选择最后一项。 1.0.0
indicator-style string 设置选择器中间选中框的样式 1.0.0
indicator-class string 设置选择器中间选中框的类名 1.1.0
mask-style string 设置蒙层的样式 1.5.0
mask-class string 设置蒙层的类名 1.5.0
immediate-change boolean false 是否在手指松开时立即触发 change 事件。若不开启则会在滚动动画结束后触发 change 事件。 2.21.1
bindchange eventhandle 滚动选择时触发 change 事件,event.detail = {value};value为数组,表示 picker-view 内的 picker-view-column 当前选择的是第几项(下标从 0 开始) 1.0.0
bindpickstart eventhandle 当滚动选择开始时候触发事件 2.3.1
bindpickend eventhandle 当滚动选择结束时候触发事件 2.3.1
<picker-view style="width: 100%;height: 250px;" bindchange="changevalue">
 <picker-view-column>
    <view wx:for="{
     
     {year}}">{
   
   {item}}</view>
 </picker-view-column>
 <picker-view-column>
    <view wx:for="{
     
     {month}}">{
   
   {item}}</view>
 </picker-view-column>
 <picker-view-column>
    <view wx:for="{
     
     {day}}">{
   
   {item}}</view>
 </picker-view-column>
</picker-view>
<view>{
   
   {myvalue}}</view>

Page({
    
    
    data: {
    
    
        year:[1990,1995,2000,2005,2010,2020,2025],
        month:[1,2,3,4,5,6,7,8,9,10,11,12],
        day:[1,5,10,15,20,25,30],
        myvalue:''

    },
    changevalue:function(e){
    
    
        //获取选中的下标集合
         let indexs = e.detail.value;
         var year = this.data.year[indexs[0]];
         var month = this.data.month[indexs[1]];
         var day = this.data.day[indexs[2]];
         this.setData({
    
    
             myvalue: this.data.myvalue = year+"-"+month+"-"+day,
         });
    }
})

滑动有声音,吓我一条

imagen-20230710162318398

radio

属性说明:

属性 类型 默认值 必填 说明 最低版本
value string radio 标识。当该radio 选中时,radio-group 的 change 事件会携带radio的value 1.0.0
checked boolean false 当前是否选中 1.0.0
disabled boolean false 是否禁用 1.0.0
color string #09BB07 radio的颜色,同 css 的color 1.0.0
<radio-group bindchange="choose">
    <radio checked="{
     
     {item.id == 2?true:false}}" wx:for="{
     
     {array}}" value="{
     
     {item.name}}">{
   
   {item.value}}</radio>
</radio-group>
<view>{
   
   {myvalue}}</view>
Page({
    
    
    data: {
    
    
      array:[
        {
    
    id:'1',name:'male',value:'男'},
        {
    
    id:'2',name:'female',value:'女'}
      ],
      myvalue:'请选择性别'
    },
    choose:function(e){
    
    
        var value = e.detail.value;
        this.setData({
    
    
            myvalue:value
        });
    }
})

imagen-20230710163211035

slider

滑动选择器

属性说明:

属性 类型 默认值 必填 说明 最低版本
min number 0 最小值 1.0.0
max number 100 最大值 1.0.0
step number 1 步长,取值必须大于 0,并且可被(max - min)整除 1.0.0
disabled boolean false 是否禁用 1.0.0
value number 0 当前取值 1.0.0
color color #e9e9e9 背景条的颜色(请使用 backgroundColor) 1.0.0
selected-color color #1aad19 已选择的颜色(请使用 activeColor) 1.0.0
activeColor color #1aad19 已选择的颜色 1.0.0
backgroundColor color #e9e9e9 背景条的颜色 1.0.0
block-size number 28 滑块的大小,取值范围为 12 - 28 1.9.0
block-color color #ffffff 滑块的颜色 1.9.0
show-value boolean false 是否显示当前 value 1.0.0
bindchange eventhandle 完成一次拖动后触发的事件,event.detail = {value} 1.0.0
bindchanging eventhandle 拖动过程中触发的事件,event.detail = {value} 1.7.0
<slider min="1" max="100" show-value="{
     
     {true}}" bindchanging="changevalue"></slider>
<view style="width:{ 
        { 
        width}};height:100rpx;background-color: green;"></view>
Page({
    
    
    data: {
    
    
        width:"10rpx",
    },
    changevalue:function(e){
    
    
        var value = e.detail.value;
        this.setData({
    
    
            width:value*5+"rpx"
        });
    }
})

imagen-20230710163238453

switch

开关选择器。

属性说明:

属性 类型 默认值 必填 说明 最低版本
checked boolean false 是否选中 1.0.0
disabled boolean false 是否禁用 1.0.0
type string switch 样式,有效值:switch, checkbox 1.0.0
color string #04BE02 switch 的颜色,同 css 的 color 1.0.0
bindchange eventhandle 点击导致 checked 改变时会触发 change 事件,event.detail={ value} 1.0.0
<switch checked="{
     
     {false}}" color="red">这是一个开关选择器</switch>
<switch checked="{
     
     {true}}" bindchange="changevalue">开关</switch>
<view style="background-color: { 
        { 
        color}};width: 100%;height: 500rpx;"></view>
Page({
    
    
    data: {
    
    
      color:'#FFFFFF'
    },
    changevalue:function(e){
    
    
        var flag = e.detail.value;
        if(flag){
    
    
            this.setData({
    
    
                color:'#FFFFFF' 
            });
        }else{
    
    
            this.setData({
    
    
                color:'#000000' 
            });
        }
    }
})

imagen-20230710163339238

表单综合练习

<form bindsubmit="submitForm">
    <input name="username" placeholder="请输入用户名" />
    <input name="password" password="{
     
     {true}}" placeholder="请输入密码" />
    <checkbox-group name="skill" style="margin-top: 25rpx;">
        请选择技能
        <view wx:for="{
     
     {skills}}">
            <checkbox id="{
     
     {item.id}}" value="{
     
     {item.name}}">{
   
   {item.value}}</checkbox>
        </view>
    </checkbox-group>
    <picker name="birthday" mode="date" start="1970-01-01" end="2000-12-31" bindchange="changeDate" style="margin-top: 25rpx">
        <view>{
   
   {birthday}}</view>
    </picker>
    <picker name="city" mode="region" bindchange="changeCity" style="margin-top: 25rpx">
        <view>{
   
   {city}}</view>
    </picker>
    <radio-group name="sex" style="margin-top: 25rpx">
      <radio value="" checked="{
     
     {true}}"></radio>
      <radio value=""></radio>
    </radio-group>
    <view style="margin-top: 25rpx">
        请选择年龄:
        <slider min="15" max="50" show-value="{
     
     {true}}" name="age"></slider>
    </view>
    <switch name="isOk" style="margin-top: 25rpx">是否保密</switch>
    <textarea name="remark" style="margin-top: 25rpx" placeholder="备注">
    </textarea>
    <button form-type="submit" type="primary" size="mini">提交</button>
    <button style="margin-left: 25rpx;" form-type="reset" type="warn"size="mini">重置</button>
</form>
Page({
    
    
    data: {
    
    
        skills:[{
    
    id:'s01',name:'Java',value:'Java'},
                {
    
    id:'s02',name:'SQL',value:'SQL'},
                {
    
    id:'s03',name:'HTML',value:'HTML'},
                {
    
    id:'s04',name:'JavaScript',value:'JavaScript'}
                ],
        birthday:'请选择出生日期',
        city:'请选择你所在地'
    },
    submitForm:function(e){
    
    
       console.log(e);
    },
    changeDate:function(e){
    
    
        this.setData({
    
    
            birthday:e.detail.value,
        });
    },
    changeCity:function(e){
    
    
        var values = e.detail.value;
        this.setData({
    
    
            city:values[0]+','+values[1]+','+values[2],
        });
        console.log(e)
    }
})

imagen-20230710163519822

导航组件

<navigator></navigator>

页面链接,类似html的超链接

属性说明:

属性 类型 默认值 必填 说明 最低版本
target string self 在哪个目标上发生跳转,默认当前小程序 2.0.7
合法值 说明
self 当前小程序
miniProgram 其它小程序
url string 当前小程序内的跳转链接 1.0.0
open-type string navigate 跳转方式 1.0.0
合法值 说明 最低版本
navigate 对应 wx.navigateTowx.navigateToMiniProgram 的功能
redirect 对应 wx.redirectTo 的功能
switchTab 对应 wx.switchTab 的功能
reLaunch 对应 wx.reLaunch 的功能 1.1.0
navigateBack 对应 wx.navigateBack 的功能 1.1.0
exit 退出小程序,target="miniProgram"时生效 2.1.0
delta number 1 当 open-type 为 'navigateBack' 时有效,表示回退的层数 1.0.0
app-id string target="miniProgram"时有效,要打开的小程序 appId 2.0.7
path string target="miniProgram"时有效,打开的页面路径,如果为空则打开首页 2.0.7
extra-data object target="miniProgram"时有效,需要传递给目标小程序的数据,目标小程序可在 App.onLaunch()App.onShow() 中获取到这份数据。详情 2.0.7
version string release target="miniProgram"时有效,要打开的小程序版本 2.0.7
合法值 说明
develop 开发版
trial 体验版
release 正式版,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。
short-link string target="miniProgram"时有效,当传递该参数后,可以不传 app-id 和 path。链接可以通过【小程序菜单】->【复制链接】获取。 2.18.1
hover-class string navigator-hover 指定点击时的样式类,当hover-class="none"时,没有点击态效果 1.0.0
hover-stop-propagation boolean false 指定是否阻止本节点的祖先节点出现点击态 1.5.0
hover-start-time number 50 按住后多久出现点击态,单位毫秒 1.0.0
hover-stay-time number 600 手指松开后点击态保留时间,单位毫秒 1.0.0
bindsuccess string target="miniProgram"时有效,跳转小程序成功 2.0.7
bindfail string target="miniProgram"时有效,跳转小程序失败 2.0.7
bindcomplete string target="miniProgram"时有效,跳转小程序完成 2.0.7

nav.wxml页面:

<view>这是navigator页面</view>
<navigator open-type="navigate" url="../demo19-picker/index">跳转到demo19</navigator>
<navigator open-type="redirect" url="../demo21-picker-view/index">跳转到demo21</navigator>
<navigator open-type="navigate" url="../test-demo/index?name=张三">跳转到test</navigator>

test-demo文件夹下的index.wxml页面

当前是test页面
<text>{
   
   {value}}</text>

test-demo文件夹下的index.js文件:

Page({
    
    
    data: {
    
    
        value:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
    
    
        if(options){
    
    
            this.setData({
    
    
                value:'hello:'+options.name,
            });
        }
    },
})

imagen-20230710164302654

媒体组件

image

<image></image>

图片。支持 JPG、PNG、SVG、WEBP、GIF 等格式

image组件默认宽度320px、高度240px

属性说明:

属性 类型 默认值 必填 说明 最低版本
src string 图片资源地址 1.0.0
mode string scaleToFill 图片裁剪、缩放的模式 1.0.0
合法值 说明 最低版本
scaleToFill 缩放模式,不保持纵横比缩放图片,使图片的宽高完全拉伸至填满 image 元素
aspectFit 缩放模式,保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。
aspectFill 缩放模式,保持纵横比缩放图片,只保证图片的短边能完全显示出来。也就是说,图片通常只在水平或垂直方向是完整的,另一个方向将会发生截取。
widthFix 缩放模式,宽度不变,高度自动变化,保持原图宽高比不变
heightFix 缩放模式,高度不变,宽度自动变化,保持原图宽高比不变 2.10.3
top 裁剪模式,不缩放图片,只显示图片的顶部区域
bottom 裁剪模式,不缩放图片,只显示图片的底部区域
center 裁剪模式,不缩放图片,只显示图片的中间区域
left 裁剪模式,不缩放图片,只显示图片的左边区域
right 裁剪模式,不缩放图片,只显示图片的右边区域
top left 裁剪模式,不缩放图片,只显示图片的左上边区域
top right 裁剪模式,不缩放图片,只显示图片的右上边区域
bottom left 裁剪模式,不缩放图片,只显示图片的左下边区域
bottom right 裁剪模式,不缩放图片,只显示图片的右下边区域
webp boolean false 默认不解析 webP 格式,只支持网络资源 2.9.0
lazy-load boolean false 图片懒加载,在即将进入一定范围(上下三屏)时才开始加载 1.5.0
show-menu-by-longpress boolean false 长按图片显示发送给朋友、收藏、保存图片、搜一搜、打开名片/前往群聊/打开小程序(若图片中包含对应二维码或小程序码)的菜单。 2.7.0
binderror eventhandle 当错误发生时触发,event.detail = {errMsg} 1.0.0
bindload eventhandle 当图片载入完毕时触发,event.detail = {height, width} 1.0.0
<image src="https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg"></image>
<image src="{
     
     {src}}" style="width: 200px; height: 200px;" mode="top"></image>
// pages/demo23-image/index.js
Page({
    
    
  data: {
    
    
    src:'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg'
  }
})

imagen-20230710164741059

video

index.wxml:

<view class="page-body">
  <view class="page-section tc">
    <video 
      id="myVideo" 
      src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400" 
      binderror="videoErrorCallback" 
      danmu-list="{
     
     {danmuList}}" 
      enable-danmu 
      danmu-btn 
      show-center-play-btn='{
     
     {false}}' 
      show-play-btn="{
     
     {true}}" 
      controls
      picture-in-picture-mode="{
     
     {['push', 'pop']}}"
      bindenterpictureinpicture='bindVideoEnterPictureInPicture'
      bindleavepictureinpicture='bindVideoLeavePictureInPicture'
    ></video>
    <view style="margin: 30rpx auto" class="weui-label">弹幕内容</view>
    <input bindblur="bindInputBlur" class="weui-input" type="text" placeholder="在此处输入弹幕内容" />
    <button style="margin: 30rpx auto"  bindtap="bindSendDanmu" class="page-body-button" type="primary" formType="submit">发送弹幕</button>
    <navigator style="margin: 30rpx auto"  url="picture-in-picture" hover-class="other-navigator-hover">
      <button type="primary" class="page-body-button" bindtap="bindPlayVideo">小窗模式</button>
    </navigator>
  </view>
</view>

índice.js:

function getRandomColor() {
    
    
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    
    
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length === 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

Page({
    
    
  onShareAppMessage() {
    
    
    return {
    
    
      title: 'video',
      path: 'page/component/pages/video/video'
    }
  },

  onReady() {
    
    
    this.videoContext = wx.createVideoContext('myVideo')
  },

  onHide() {
    
    

  },

  inputValue: '',
  data: {
    
    
    src: '',
    danmuList:
    [{
    
    
      text: '第 1s 出现的弹幕',
      color: '#ff0000',
      time: 1
    }, {
    
    
      text: '第 3s 出现的弹幕',
      color: '#ff00ff',
      time: 3
    }],
  },

  bindInputBlur(e) {
    
    
    this.inputValue = e.detail.value
  },

  bindButtonTap() {
    
    
    const that = this
    wx.chooseVideo({
    
    
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: ['front', 'back'],
      success(res) {
    
    
        that.setData({
    
    
          src: res.tempFilePath
        })
      }
    })
  },

  bindVideoEnterPictureInPicture() {
    
    
    console.log('进入小窗模式')
  },

  bindVideoLeavePictureInPicture() {
    
    
    console.log('退出小窗模式')
  },

  bindPlayVideo() {
    
    
    console.log('1')
    this.videoContext.play()
  },
  bindSendDanmu() {
    
    
    this.videoContext.sendDanmu({
    
    
      text: this.inputValue,
      color: getRandomColor()
    })
  },

  videoErrorCallback(e) {
    
    
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  }
})

imagen-20230710165832218

Supongo que te gusta

Origin blog.csdn.net/qq_66345100/article/details/131701864
Recomendado
Clasificación