小程序开发笔记
小程序开发
一、小程序基础组件
<view> </view>
<text> </text>
//https://developers.weixin.qq.com/miniprogram/dev/component/input.html
// type:text 文本输入键盘
// number 数字输入键盘
// idcard 身份证输入键盘
// digit 带小数点的数字键盘
// safe-password 密码安全输入键盘 指引
<input> </input>
//https://developers.weixin.qq.com/miniprogram/dev/component/button.html
<button> </button>
二、函数和事件
函数
//函数的两种声明方式
onLoad:function(){
}
onLoad(){
}
//函数的调用
test(){
this.test2("csm")
},
test2(name){
//日志打印
console.log("I am",name)
}
可以根据日志打印的内容过滤日志:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KbpcakH1-1639656615061)(C:\Users\19783\AppData\Roaming\Typora\typora-user-images\image-20211213193722821.png)]
点击事件
//bindtap会执行后台的getValue函数
<text> bindtap="getValue"</text>
//每当输入框值改变就会执行
<input bindinput="getInput"></input>
getInput(value){
//输入用户输入的值
console.log(value.detail.value)
}
三、变量
变量声明与变量类型转换
//声明 变量类型有:Number, String, Boolean, Undefined, Null
var value = 0
let value2 = 0 //用来声明局部变量。它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效,而且有暂时性死区的约束
//获取数据类型
console.log(typeof(value))
//数据类型转换,转字符
var a = 1 + ""
var b = true + ""
var c = 1
var str = c.toString()
var str2 = String(c)
//其他类型转数值
var d = "2"
var n = Number(d) //浮点,整数都可以转换
var f = parseFloat(d)
var i = parseInt(d)
数组和对象
//数组
var nums = [1,2,3]
var nums2 = new Array()
//长度
nums.length
//末尾添加元素
nums[3] = "test"
nums.push("test")
nums.push("aaa",4,5,6)
//在开头添加元素
nums.unshift(0)
//删除最后元素
nums.pop()
//删除开头元素
nums.shift()
//对象
//第一种
var obj = {
name:"bert",
age:18,
fun:function(){
console.log("bert test");
}
}
//第二种
var obj2 = new Object();
obj2.name = "csm"
obj2.fun = function(){
console.log("csm test")
}
//第三种,构造函数,适用于批量创建对象
function Obj(name){
this.name = name,
this.fun = function(){
console.log("xxc test")
}
}
var obj3 = new Obj("xxc")
obj3.fun()
内置对象
参考文档 :MDN https://developer.mozilla.org/zh-CN/docs/Web/javaScript
//随机数 0 <= x < 1
Math.random()
Math.random()*(max - min) + min
Math.round(x)
返回四舍五入后的整数
Math.ceil(x)
返回大于一个数的最小整数,即一个数向上取整后的值。
Math.floor(x)
返回小于一个数的最大整数,即一个数向下取整后的值
Math.pow(x, y)
返回一个数的 y 次幂。
Math.max([x[, y[, …]]])
返回零到多个数值中最大值。
Math.min([x[, y[, …]]])
返回零到多个数值中最小值。
Math.abs(x)
返回一个数的绝对值。
//日期
var date = new Date()
var date2 = new Date(2021,12,14,19,29)
var date3 = new Date('2021-12-14 19:30:00')
var date4 = new Date(1000)//时间戳 ms
//日期获取
var date = new Date()
var time = date.getTime()//时间戳
date.getFullYear()//获取nian
date.getMonth()
date.getHours()
date.getMinutes()
date.getSeconds()
//数组
var arr = new Array()
console.log(arr instanceof Array)
console.log(Array.isArray(arr))
//翻转数组
arr.reverse()
//排序数组,默认是转为字符串排序
arr.sort()
//数值数组排序
arr.sort(function(a,b){
return a-b //升序
})
arr.indexOf(3) //返回3的第一个索引
arr.lastIndexOf(3) //返回3的最后一个索引
arr.toString() //数组转字符串
四、数据绑定
<!-- 数据绑定的两种方式-->
<text>{{name}}</text>
<img src="{{src}}" />
Page({
data:{
name:"bert",
src:"image/img1.png"
},
getInput(event){
//不会实时显示
this.data.name = "csm"
//数据的动态绑定,实时显示
this.setData({
name:event.detail.value
})
}
})
//绑定全局变量
const app = getApp()
app.globalData.name = "bert"
五、wxml页面渲染
<!-- 条件渲染-->
<text wx:if="{{age => 18}}"> 您满18,可以进网吧!</text>
<text wx:if="{{age < 18}}"> 您不满18,不可以进网吧!</text>
<text wx:if="{{cj >= 90}}">优秀</text>
<text wx:elif="{{cj>=60}}">及格</text>
<text wx:else="{{cj<60}}">不及格</text>
<!--循环渲染 list:[{name:"csm",wechat:"11111"},{name:"bert",wechat:"22222"}] -->
<view wx:for="{{list}}">
<view>{{item.name}}</view>
<view>{{item.wechat}}</view>
</view>
六、WXSS样式美化
菜鸟教程:https://www.runoob.com/css/css-tutorial.html
颜色
background-color:#FFFFF;
文本
/*居中*/
text-align:center
/*文本下划线*/
text-decoration:underline;
/*字体*/
font-size:30px;
边距
padding:10px;
margin:10px;
border:1px solid red;
border-radius:10px;
适配问题
//px 与rpx的转换
//整个屏幕宽:750rpx,在iphone6下1px = 2rpx
flex布局:
display:flex;
flex-direction:column;
justify-content:center; //水平
align-items:center; //垂直
七、组件
图片:https://developers.weixin.qq.com/miniprogram/dev/component/image.html
//默认宽高:320px *240px
<image src="/images/picture.png" ></image>
//模式:
<image mode=""></image>
//懒加载
<image lazy-load="true"></image>
视频:https://developers.weixin.qq.com/miniprogram/dev/component/video.html
<video show-play-btn src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
轮播图:https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
<!-- 方法1 -->
<swiper indicator-dots indicator-active-color="blue" autoplay>
<swiper-item class="num1">
<image class="img" src="https://img0.baidu.com/it/u=986567382,3731968355&fm=26&fmt=auto"></image>
</swiper-item>
<swiper-item class="num2">
<image class="img" src="https://img0.baidu.com/it/u=599045285,3012701325&fm=26&fmt=auto"></image>
</swiper-item>
<swiper-item class="num3">
<image class="img" src="https://img2.baidu.com/it/u=182878036,307711730&fm=253&fmt=auto&app=120&f=JPEG?w=724&h=439"></image>
</swiper-item>
</swiper>
<!-- 方法2 -->
<swiper indicator-dots indicator-active-color="blue" autoplay>
<swiper-item wx:for="{{imageList}}">
<image class="img" src="{{item}}"></image>
</swiper-item>
</swiper>
TabBar:
页面切换,在app.js添加:
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件",
"iconPath":"",
"selectedIconPath":""
}, {
"pagePath": "page/API/index",
"text": "接口",
"iconPath":"",
"selectedIconPath":""
}]
}
navigator页面跳转:https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html
<navigator url="/page/navigate/navigate?title=navigate" open-type="redirect" hover-class="navigator-hover">跳转到新页面</navigator>
navigate | 对应 wx.navigateTo 或 wx.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 |
API操作页面跳转:
//带数据的页面跳转
goNew(e){
var title = e.currentTarget.dataset.title
urlnew = '/pages/detail?title='+title
wx.navigateTo({url:urlnew})
}
<view wx:for="{{list}}">
<view class="item" bindtap="goNew" data-title="{{item}}">{{item}</view>
</view>
//获取参数
onLoad(e){
}
打开别的小程序:
wx.navigateToMiniProgram({
appId:""
})
scroll-view:https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html
<scroll-view>
内容区域
</scroll-view>
属性 | 类型 | 默认值 | 必填 | 说明 | 最低版本 |
---|---|---|---|---|---|
scroll-x | boolean | false | 否 | 允许横向滚动 | 1.0.0 |
scroll-y | boolean | false | 否 | 允许纵向滚动 | 1.0.0 |
upper-threshold | number/string | 50 | 否 | 距顶部/左边多远时,触发 scrolltoupper 事件 | 1.0.0 |
八、API
1、授权登录
获取用户信息
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true,
imgPath:res.userInfo.avatarUrl
})
console.log("授权成功")
},
fail:(res)=>{
console.log("授权失败")
}
})
//如果写成success(res){ this.setData({})}会报错,不能用this,需要在外面定义var that = this
退出登录
unlogin(){
this.setData({
userInfo: null,
hasUserInfo: false
})
wx.setStorageSync("user", null) //清除缓存中的用户信息
}
缓存用户信息:
wx.setStorageSync("user", res.userInfo)
取出缓存中的用户信息:
onLoad: function (options) {
var user = wx.getStorageSync('user')
console.log(user)
}
2、生命周期
页面生命周期:
https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html
属性 | 类型 | 默认值 | 必填 | 说明 |
---|---|---|---|---|
data | Object | 页面的初始数据 | ||
options | Object | 页面的组件选项,同 Component 构造器 中的 options ,需要基础库版本 2.10.1 | ||
onLoad | function | 生命周期回调—监听页面加载 | ||
onShow | function | 生命周期回调—监听页面显示 | ||
onReady | function | 生命周期回调—监听页面初次渲染完成 | ||
onHide | function | 生命周期回调—监听页面隐藏 | ||
onUnload | function | 生命周期回调—监听页面卸载 | ||
onPullDownRefresh | function | 监听用户下拉动作 | ||
onReachBottom | function | 页面上拉触底事件的处理函数 | ||
onShareAppMessage | function | 用户点击右上角转发 | ||
onShareTimeline | function | 用户点击右上角转发到朋友圈 | ||
onAddToFavorites | function | 用户点击右上角收藏 | ||
onPageScroll | function | 页面滚动触发事件的处理函数 |
//分享小程序到朋友圈
onShareAppMessage:function(){
return {
title:"来自xxx的分享"
}
},
onShareTimeline:function(){
return {
title:'分享xxx小程序到朋友圈'
}
}
小程序生命周期:https://developers.weixin.qq.com/miniprogram/dev/reference/api/App.html
属性 | 类型 | 默认值 | 必填 | 说明 | 最低版本 |
---|---|---|---|---|---|
onLaunch | function | 否 | 生命周期回调——监听小程序初始化。 | ||
onShow | function | 否 | 生命周期回调——监听小程序启动或切前台。 | ||
onHide | function | 否 | 生命周期回调——监听小程序切后台。 |