在微信小程序中使用spilt切割数组

在微信小程序中使用spilt切割数组,第1张

程序需要在 wxml 页面使用 spilt 切割数组,是不是发现怎么用发现都不对,后来看到网上一点的信息才知道原来在wxml中使用复杂的运算是不行的,本来想着让后端做处理,后来想到了小程序是支持 wxs 方法的。下面是处理的示例大家可以参考:

<wxs module="fn">

    module.exports={

        split:function(str){

            return str.split(',')

        }

    }

</wxs>

{{fn.split(item.files)}}

这个问题,如果条件允许,最好在后台程序中解决,在后台读取出图片路径数据后,立刻就分割为数组,然后把所有数据按json格式返回给小程序,小程序再把它放入page的data中,这样小程序无须大的改动就能显示图片了。

如果这个办法行不通,也可以在小程序获得后台返回的json数据后,先把其中的图片路径数据(即用:分隔的多个图片路径的字符串)用split分割为数组,再放入page的data中,这样小程序的wxml文件也不需要大改就能显示多个图片了。

如果实在懒得很,后台返回的数据一股脑的直接放到page的data中,那么还有最后的一种解决办法,就是在wxml文件中通过小程序自身的wxs语言实时分割路径字符串,比如(假定图片字段名为image):

<wxs module="fun"> module.exports = { imgPathSplit: function(s) { if (s) return s.split(":") } }</wxs>

然后在需要循环显示图片的地方加入代码(只是示例):

<image wx:for="{{fun.imgPathSplit(item.image)}}" wx:key="*this" mode="aspectFill" src="{{item}}"></image>

这样,在小程序渲染页面时就会实时对路径字符串进行分割,再循环显示出图片来。

小程序的wxs功能可以让wsmxl可以调用和编写js,基本上wxs和JS无关系,只是语法形式很相似。

如下写了两个关于时间的函数,并将它们导出,

<wxs module="m1">

var getMax = function(flightDate) {

    var now = getDate().getDate()

    var flDate = getDate(flightDate).getDate()

    if( now <flDate ){

      return '+1'

    }else{

      return ''

    }

}

var formartTime = function(flightDate,format){

  if(flightDate){

    var realDate = getDate(flightDate)

    function timeFormat(num) {

      return num <10 ? '0' + num : num

    }

    var date = {

      "Y": timeFormat(realDate.getFullYear()),

      "M": timeFormat(realDate.getMonth() + 1),

      "d": timeFormat(realDate.getDate()),

      "h": timeFormat(realDate.getHours()),

      "m": timeFormat(realDate.getMinutes()),

      "s": timeFormat(realDate.getSeconds()),

      "q": Math.floor((realDate.getMonth() + 3) / 3),

      "S": realDate.getMilliseconds(),

    }

    if (!format) {

      format = "yyyy-MM-dd hh:mm:ss"

    }

    if( format == 'hh:mm' ){

        return date.h+':'+date.m

    }else{

        return date.h+':'+date.m

    }

  }else{

    return false

  }

}

module.exports.getMax = getMax

module.exports.formartTime = formartTime

</wxs>

可在页面添加如下使用:

m1.formartTime()  m1.getMax()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8058945.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存