微信小程序|页面的生命周期函数onLoad
欢迎点击「算法与编程之美」↑关注我们!
本文首发于微信公众号:"算法与编程之美",欢迎关注,及时了解更多此系列文章。
问题描述
相信小程序的初学者对js页面是很模糊的总感觉看不懂,其实js页面总的来说就是一个Page()函数。用Page()函数来注册一个页面,接受一个object参数,实现页面的生命周期函数 、初始数据、事件处理函数。下面简单介绍onLoad生命周期函数实现页面跳转。
解决方案
onLoad函数对页面状态数据的初始化,是生命周期回调—监听页面加载。下面以一个轮播图为例来介绍onLoad生命周期函数。
首先在wxml中对页面内容以及在wxss中的内容属性进行设置。
current:绑定到js中的onLoad函数来控制默认切换的页面,也可以直接输入页面的索引来控制(例如:current:3)
swiper:轮播图 的标签
wx:for:对轮播图循环渲染到页面
{{item.name}}:循环控制变量
bindtap:点击事件绑定到onLoad,点击按钮返回到绑定的页面
wx:if:条件语句
表1 wxml
<swiper indicator-dots="{{true}}" current="{{currentindex}}"> <swiper-item wx:for="{{novel}}" wx:key="key"> <view class="container card"> <image src="{{item.imagePath}}"></image> <text>第{{index+1}}部:{{item.name}}</text> <text>评价:{{item.comment}}</text> <text bindtap="onLoad" wx:if="{{index <novel.length-1}}">返回尾页</text> </view> </swiper-item> </swiper> |
表2 wxss
.container1{ height: 100vh; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .novel{ display: flex; } .novel-image{ width: 200rpx; height: 200rpx } .novel-swiper{ height: 90vh } .card{ height: 100%; width: 100% } .return-button{ position: absolute; right: 30px; top: 20px; font-size: 25rpx; font-style: italic; border: 2px solid yellow; border-radius: 20% } |
在js的Page()函数中定义数据并形成对象数组以及定义生命周期函数onLoad。
setData:函数用于将数据从逻辑层发送到视图层(异步),同时改变对应的 this.data 的值(同步)。
表3
Page({ data: { novel: [ { name: "《平凡的世界》", comment: "中国当代城乡社会生活的长篇小说", imagePath: "/pages/img/小说1.jpg" }, { name: "《骆驼祥子》", comment: "优秀的现实主义小说", imagePath: "/pages/img/小说2.jpg" }, { name: "《家》", comment: "入选20世纪中文小说100强(第8位)", imagePath: "/pages/img/小说3.jpg" }, { name: "《悲惨世界》", comment: "雨果现实主义小说中最成功的一部代表作", imagePath: "/pages/img/小说4.jpg" }, ], }, onLoad:function(options){ this.setData({ currentindex:this.data.novel.length-1 }) } }) |
效果图:每次打开小程序初始页面都会在尾页,浏览其他页面后点击返回尾页页面将跳转至尾页。
图1
图2
其他页面的生命周期函数:
图3
结语
在用页面周期函数的时候一定要掌握几种页面周期函数的用法,不能张冠李戴,需要哪一方面的作用就用哪种的函数。而且js中的括号特别多注意不要遗漏和多余。
END
主 编 | 王文星
责 编 | 江汪霖
where2go 团队
微信号:算法与编程之美
长按识别二维码关注我们!
温馨提示:点击页面右下角“写留言”发表评论,期待您的参与!期待您的转发!