首页 > 编程语言 >微信小程序wxs封装使用以及公共js组件封装

微信小程序wxs封装使用以及公共js组件封装

时间:2023-01-30 21:12:24浏览次数:34  
标签:封装 wxs 微信 js getMax let date

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

标签:封装,wxs,微信,js,getMax,let,date
From: https://www.cnblogs.com/wang-fan-w/p/17077246.html

相关文章