微信小程序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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值