本文共 3709 字,大约阅读时间需要 12 分钟。
template模板实现样式复用,只用写一遍wxml和wxss,在需要用到模板样式的地方将模板引入就可以,大大提高了代码的简洁性。
创建文件夹:
1.先写静态样式
templateStudy.wxml文件:
templateStudy.wxss文件:
page{ background-color: #f0f0f0;}.container{ margin: 20rpx;}.list-item{ background-color: white; border-radius: 10rpx;}.title{ margin: 20rpx; line-height: 80rpx; flex-direction: row; display: flex; border-bottom: 1rpx solid #f0f0f0;}.info{ margin: 20rpx; flex-direction: row; display: flex; line-height: 60rpx; font-size: 34rpx;}.Sno{ position: absolute; right: 50rpx;}
运行结果:
2.将写好的样式转换成template模板
(1)创建文件夹存放template模板
(2)编写template模板,name作为模板的名字,引用的时候会使用到
student-item-template.wxml:
student-item-template.wxss:
.list-item{ background-color: white; border-radius: 10rpx;}.title{ margin: 20rpx; line-height: 80rpx; flex-direction: row; display: flex; border-bottom: 1rpx solid #f0f0f0;}.info{ margin: 20rpx; flex-direction: row; display: flex; line-height: 60rpx; font-size: 34rpx;}.Sno{ position: absolute; right: 50rpx;}
(3)在要用到template模板的templateStudy.wxml文件中引入模板
在对应的templateStudy.wxss文件中引入模板样式
@import "../student-item/student-item-template.wxss";
在templateStudy.wxml文件template标签中用is指定使用的template模板名,变量引用有两种方式:
第一种方式:
//这里data使用{ {...item}},那么在template中引用变量的时候就直接使用变量名
第二种方式:
//这里data使用{ {item}},那么在template中引用变量的时候就直接使用item.变量名
(4)在templateStudy.js文件中获取本地静态数据库的数据进行渲染
本地数据库数据:
var local_database = [ { username:"小红", classname:"三(8)班", Sno:"777" }, { username: "小名", classname: "三(8)班", Sno: "666" }, { username: "小花", classname: "三(8)班", Sno: "888" },]module.exports = { studentsList: local_database}
templateStudy.js文件中引入本地数据库:
var postsData = require('../../../data/students.js')
onLoad函数中获取数据:
onLoad: function (options) { this.setData({ studentsList: postsData.studentsList }); console.log(this.data.studentsList); },
控制台打印出的数据:
运行结果:
3.完整代码
templateStudy.wxml:
templateStudy.wxss:
@import "../student-item/student-item-template.wxss";page{ background-color: #f0f0f0;}.container{ margin: 20rpx;}
templateStudy.js:
var postsData = require('../../../data/students.js')Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.setData({ studentsList: postsData.studentsList }); console.log(this.data.studentsList); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }})
student-item-template.wxml:
student-item-template.wxss:
.list-item{ background-color: white; border-radius: 10rpx;}.title{ margin: 20rpx; line-height: 80rpx; flex-direction: row; display: flex; border-bottom: 1rpx solid #f0f0f0;}.info{ margin: 20rpx; flex-direction: row; display: flex; line-height: 60rpx; font-size: 34rpx;}.Sno{ position: absolute; right: 50rpx;}
转载地址:http://mlssi.baihongyu.com/