> 文章列表 > 【小程序】小程序组件-1

【小程序】小程序组件-1

【小程序】小程序组件-1

一. form组件的使用

这个点自己写的时候卡了好久,比较有感悟。

首先明确一点,为什么需要form。

form可以封装一个模块,这个模块里可以有多个input操作,多个输出接口,多个按键,但是至多有两个关键按键:submit和reset

submit执行提交之后对整个模块进行操作的函数。对应的buttom的form-type="submit"

reset执行对整个模块进行复位的函数。对应的buttom的form-type="reset"

(其实只是起名这么起而已,真的函数怎么样,其实随你)

刚刚提到了多个input操作,有个问题,e.detail.value获得的是整个触发函数对应的模块里输入的全部内容,那么怎么分清哪个是哪个input输入的呢。

答案是给input起名字,比如name="cels",获取它输入的值可以变为e.detail.value.cels

<view class="box"><view><form bindsubmit="changeM" bindreset=""><input name="cels" type="digit" placeholder="请输入人民币金额" auto-focus="true" /><view class="layout"><button type="primary" form-type="submit">提交</button><button type="warn" form-type="reset">复原</button></view><view>{{dollar}}</view></form></view></view>
const app=getApp()
var C;
Page({/* 页面的初始数据*/data: {},changeM:function(e){C=parseInt(e.detail.value.cels);this.setData({dollar:(C/6.08).toFixed(4)})}
})

二. 看一个实例

做一个小程序,要求用户输入三角形三条边的长度,当能构成三角形时显示三角形的周长,不能构成则显示提示“三角形两边之和需要大于第三边”。

显示提示不是指自己输在屏幕上的文本,是那种提交成功样式的灰框框,引进一个新组件,this.showToast({

        title:' '

}) title里就是你想显示在灰框框中的东西。

<view class="box"><form bindsubmit="changeM"><input name="cel1" type="digit" placeholder="请输入第一条边的边长"/><input name="cel2" type="digit" placeholder="请输入第二条边的边长"/><input name="cel3" type="digit" placeholder="请输入第三条边的边长"/><button form-type="submit" type="primary">提交</button><view>三角形周长为:{{perimeter}}</view></form>
</view>
// logs.js
const util = require('../../utils/util.js')Page({data: {logs: []},onLoad() {this.setData({logs: (wx.getStorageSync('logs') || []).map(log => {return {date: util.formatTime(new Date(log)),timeStamp: log}})})}
})

三. 单选框和复选框

复选框checkbox,自带封装组件为checkbox-group

单选框radio,自带封装组件为radio-group

封装组件要做的是记录被用户选择的组件中的框的value,同上,用e.detail.value取出来

这里的例子是对一行字进行动态渲染,可选渲染在复选框和单选框中

<view class="box"><text style="font-size: {{myFontsize}}; font-weight: {{myBold}}; font-style: {{myItalic}}; text-decoration: {{myUnderline}};">苏州大学</text><checkbox-group bindchange="changeCheckbox"><checkbox value="isBold">加粗</checkbox><checkbox value="isItalic">斜体</checkbox><checkbox value="isUnderline">加下划线</checkbox></checkbox-group><radio-group bindchange="changeRadio"><radio value="15px">15px</radio><radio value="25px">25px</radio><radio value="40px">40px</radio></radio-group>
</view>
const app=getApp()
var C;
Page({/* 页面的初始数据*/data: {},changeCheckbox:function(e){C=e.detail.value;for(var i=0;i<C.length;i++){if(C[i]=='isBold'){this.setData({myBold:'bold'})}if(C[i]=='isItalic'){this.setData({myItalic:'italic'})}if(C[i]=='isUnderline'){this.setData({myUnderline:'underline'})}}},changeRadio:function(e){this.setData({myFontsize:e.detail.value})}
})
radio,checkbox{font-size: 15px;display:inline-flex;flex-direction: row;margin:10px;
}