微信小程序开发基础详解
1、结构
- util.js 工具类
- app.js 全局工具函数
- app.json 小程序配置
- app.wxss 全局样式
2、生命周期
- onLoad(options) 页面加载时触发,可获取路径中的参数(1)
- onReady() 页面渲染完成(1)
- onShow() 页面显示/切入前台触发(N)
- onHide() 页面隐藏/切入后台时触发(N)
- onPullDownRefresh() 监听用户下拉动作,此事件需要在app.json文件中window节点中"开启全局的下拉刷新"enablePullDownRefresh":true,才能触发它
- onReachBottom() 上拉触底事件,需要当前页内容超过一屏幕
- onPageScroll() 滚动事件
- onShareAppMessage() 自定义分享
- onUnload() 页面写在
3、wx语法
循环- wx:for="{{}}"
- wx:key="{{}}" 可以不写 写了节约性能
- wx:for-index="key" 不写默认 index
- wx:for-item="val" 不写默认item
- wx:if="{{}}"
- wx:elif="{{}}"
- wx:else
4、模块引入
import 方法 定义模块<template name=''> 内容{{}} template>template 可以定义多个 使用
<import src='../' /> <template is='name' data='{{title:"sd"}}'/>is 模块名称 data 数据 include 方法
5、设置数据 this.setData({})
6、事件
bind 冒泡 catch 非冒泡 常见事件:tap touch相关 写法:bind:tap='click'7、事件对象
type 类型 timeStamp 时间 target 属性值 currentTarget 属性值8、属性类型
Boolean Number String Array Object EventHandler(事件处理函数名)9、共同属性
id class style hidden(隐藏) data-*(自定义属性) bind*/catch*10、自定义组件
1- 新加组件(工具新加component) 2- 需要引入组件的页面配置文件 json中定义 name path,{ "usingComponents": { // 在父模板中调用的标签名 组件的路径 "com-name": "path/to/the/custom/component" } }3- 页面中调用组件
11、组建通信
父级-子集 原理:类似于vue 自定义属性--properties接收 父级12、wxs模块
写法与js类似,不知此ES6 tools.wxsfunction mysub(str,len){ return ... } module.exports={ mysub:mysub }引入与使用
<wxs src='../../tools.wxs' module='tools'/> <view>tools.mysub('hfghaf')view>
13、网络请求
1-设置请求超时时间 app.json"networkTimeout":{ "request":10000 }2-请求 http.js
const http = ({url,data={},method='Get',header={}})=>{
wx.showLoading({
title:'加载中'
})
return new Promise((resolve,reject)=>{
wx.request({
url,
method,
success:res=>{
resolve(res)
},
fail:()=>{
reject('fail')
},
complete:()=>{
wx.hideLoading()
}
})
})
}
3-配置请求地址
config uri.js
const host = 'http://localhost/api/v1' export default { new:'${host}/news' }4-请求模型
models newsModels.js
import http from '../utils/http' import config from '../config/uri' // 获取新闻列表 export const getNew=(page=1)=>{ return http({ url:config.news }) }5-调用
import {getNews} from '../../models/newsModel'
getNews().then(res=>{
this.setData({
news:res.data
})
})
14、缓存
没有过期时间,单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。
class Cache { /* 1、设置缓存 单位毫秒 */ set(key, value, expire = 36000) { expire = Date.now() + expire * 1000 //原有的数据改成对象,加上缓存时间 let data = { expire, value } wx.setStorage({ key, data, }); } /* 2、获取缓存 */ get(key) { if (this.has(key)) { return '' } return wx.getStorage(key).value } /* 3、清理缓存 */ remove(key) { wx.removeStorage({ key: key }); } }