第三周
3.项目开发阶段
组件化开发优点
-
组件复用
-
代码分离
3.3 生命周期函数
官方文档https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page-life-cycle.html
onload
:监听页面加载,最先被触发
onReady
:监听页面初次渲染完成
onShow
:监听页面显示
onHide
:监听页面隐藏
onUnload
:监听页面卸载
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
}
3.4 向服务器发送请求
https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
wx.request
https://autumnfish.cn/api/joke/list?num=3
开发阶段不校验域名合法性
同步异步与回调函数
回调函数
success
:接口调用成功的回调函数
fail
:接口调用失败的回调函数
传统解决this
指向
在回调函数外部先保存this
状态let that =this
,然后在回调函数内部调用that
ES6中解决
使用箭头函数
success:(res) => {
console.log(this.data)
}
使用promise解决回调地域的问题
二次封装
新建config.js
新建util
文件夹,http.js
文件
在http.js
中进行请求封装
导出模块
第一种
export const config = {
api_base_url: '',
appkey: ''
}
export let fn1 = function() {
}
第二种
export {config, fn1}
导入模块
import { HTTP } from '../../util/http.js'
错误异常处理
wx.showToast({
title: '错误',
icon: 'none',
duration: 1500
})
定义错误处理函数
_show_error(error_code) {
if (!error_code) {
error_code = 1;
}
const tip = tips[error_code];
wx.showToast({
title: tip ? tip : tips[1],
icon: 'none',
duration: 2000
})
}
使用models
将发生请求的方法封装到models
下的模块中
models\classic.js
import {HTTP} from '../util/http.js'
class ClassicModel extends HTTP {
getLatest(sCallback){
this.request({
url:'classic/latest',
success:(res)=>{
sCallback(res);
}
})
}
}
export {ClassicModel}
获取首页数据并渲染到页面中
设置数据
setData({
classic:res
})
页面渲染流程
- 加载服务器数据
- setData数据绑定
- 传递组件属性
data
中的数据也是通过setData
来进行更新
movie
组件
在components
下新建组件
classic\movie
<view hidden="{{hidden}}" class="classic-container">
<image class="classic-img" src="{{img}}"></image>
<image class="tag" src="/components/images/movie@tag.png"></image>
<text class="content">{{content}}</text>
</view>
设置movie
组件属性
properties: {
img:String,
content:String
}
在classic.json
文件中注册组件
"v-movie": "/components/classic/movie/index"
在页面中使用组件
<v-movie img="{{classic.image}}" content="{{classic.content}}"></v-movie>
改进like
组件,将点赞和取消点赞事件处理写在事件的使用方
触发自定义事件
triggerEvent
方法
Component({
properties: {},
methods: {
onTap: function(){
var myEventDetail = {} // detail对象,提供给事件监听函数
var myEventOption = {} // 触发事件的选项
this.triggerEvent('myevent', myEventDetail, myEventOption)
}
}
})