微信小程序开发极简入门(四):文件导入
样式导入
在根目录下(与pages目录同级)创建common目录,并创建common.wxss:
.red_big_text {
color: red;
font-size: xx-large;
}
在具体页面的wxss文件中引用:
@import "../../common/common.wxss";
就可以在页面的wxml中使用common的样式了。就当是css就行。
脚本导入
遵循CommonJS规范。
在根目录下(与pages目录同级)创建utils目录,并创建utils.js:
const formatDateTime = function (date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
function unixTimeStampToDate(timestamp) {
const date = new Date(timestamp);
return date.toLocaleDateString();
}
const unixTimeStampToDateTime = function (timestamp) {
const date = new Date(timestamp);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}
const unixTimeStampToDefaultDateTime = timestamp => {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
module.exports = {
formatDateTime: formatDateTime,
unixTimeStampToDate: unixTimeStampToDate,
unixTimeStampToDateTime: unixTimeStampToDateTime,
unixTimeStampToDefaultDateTime: unixTimeStampToDefaultDateTime
}
在具体页面的js中导入并使用:
const util=require('../../utils/util.js')
Page({
onLoad() {
this.setData({
nowDateTime:util.formatDateTime(new Date()),
unixDate:util.unixTimeStampToDate(-639075600000),
unixDateTime:util.unixTimeStampToDateTime(-639075600000),
unixTimeToDefaultDateTime:util.unixTimeStampToDefaultDateTime(-639075600000)
})
}
})
{{nowDateTime}}
{{unixDate}}
{{unixDateTime}}
{{unixTimeToDefaultDateTime}}
模板导入
在根目录下(与pages目录同级)创建template目录--productlist目录--productlist的page。
productlist.wxss
.productList{
display: flex;
margin-top: 10rpx;
}
.productList .productImg{
width: 200rpx;
height: 200rpx;
background-color: seagreen;
}
.productList .productInfo{
flex: 1;
background-color: sienna;
}
productlist.wxml
{{productImg}}
{{productId}} {{productName}} {{price/100}}元
就是普通的wxml页面的写法,关键点是template标签及name属性。
在新的page里引入模板。
在wxss导入样式:
@import "../../template/productlist/productlist.wxss";
.scrollarea {
flex: 1;
overflow-y: hidden;
}
在js里加一些数据:
data:{
productList:[
{"productImg":"产品图片1","productId":"1","productName":"商品名称1","price":10000},
{"productImg":"产品图片2","productId":"2","productName":"商品名称2","price":22200}
]
}
在wxml导入模板:
关键点就是import标签导入模板文件,然后用template标签和is属性指向要使用的模板name。
要传递数据到模板文件,如果用{{...数据变量}},则模板里面直接用属性名即可{{productName}}。
如果直接用{{数据变量}},则模板文件里面要用{{item.productName}}。