微信小程序wxs封装使用以及公共js组件封装
wxs封装
wxs
可以直接写在wxml
页面中,并且在对应的位置调用,比如在{{ xxx.xxx() }}
调用wxs
的函数
<view>
<view>第{{m1.getMax(1)}}天</view>
</view>
<wxs module="m1">
var getMax = function(index) {
if(index == 1){
return '一'
} else {
return '二'
}
}
module.exports = {getMax : getMax}; // 导出getMax方法
</wxs>
注意
var getMax
这个位置只能使用var
封装
1、在小程序的根目录新建一个wxs
文件夹,内部新建文件,文件扩展名wxs
。这里新建一个getMax.wxs
文件举例。
2、在num.wxs
文件中写入方法
var getMax = function(index) {
if(index == 1){
return '一'
} else {
return '二'
}
}
module.exports = {getMax : getMax}; // 导出getMax方法
3、在wxml
页面中引入
// 在页面中使用 module名.方法名()
<view>第{{getMax.getMax(index + 1)}}天</view>
// 引入getMax.wxs
<wxs src="../wxs/getMax.wxs" module="getMax"></wxs>
js公共组件封装
此处演示时间戳转时间的封装:
封装js
新建封装的js
function timeExChange(time){
// 时间戳
let timestamp = time
let date = new Date(parseInt(timestamp) * 1000 );
let Year = date.getFullYear();
let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
let GMT = Year + '-' + Moth + '-' + Day + ' '+ Hour +':'+ Minute + ':' + Sechond;
return GMT
}
// 此处要使用微信小程序的模板导出,es6导出会报错
module.exports = {
timeExChange: timeExChange
};
页面使用
在需要使用的js
中引入
import { timeExChange } from '../TimeExchange/time'
let time = timeExChange(1662537367)
console.log(time ) // 2022-09-07 15:56:07
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)