微信小程序使用template标签实现五星评分功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序使用template标签实现五星评分功能

T丶快乐知己丬   2020-05-16 我要评论

前言

微信小程序特点“无须安装,无须卸载,触手可及,用完即走”,适合轻量级应用快速开发。小程序模版思想是它开发的核心思想,可以帮助开发者减少很多重复代码,我们来看看怎么在小程序中实现市面上常用的评分组件, 看看效果图:

创建模版

wxml文件:

以<template>为根节点,添加name属性用来区分不同模版:

<template name="starsTemplate">
 <view class='stars-container'>
  <view class='stars'>
  <block wx:for="{{stars}}" wx:for-item="i" wx:key="position">
   <image wx:if="{{i}}" src='/images/icon/star.png'></image>
    <!-- <image wx:elif="{{i==2}}" src='/images/icon/none-star.png'></image> -->
    <image wx:else src='/images/icon/none-star.png'></image>
  </block>
  </view>
  <text class='star-score'>{{score}}</text>
 </view>
</template>

wxss文件:

这里我们采用小程序推荐使用flex模型,横向排列五颗星星图片。

.stars-container {
 display: flex;
 flex-direction: row;
}
.stars {
 display: flex;
 flex-direction: row;
 height: 17rpx;
 margin-right: 24rpx;
 margin-top: 6rpx;
}
.stars image {
 padding-left: 3rpx;
 height: 17rpx;
 width: 17rpx;
}
.star-score {
 color: #1f3463;
}

模版使用

引用wxml模版:

<import src="../stars/stars-template.wxml" /> <!--这里引用模板文件最好使用相对路径-->
<template is="starsTemplate" data="{{stars:stars,score:average}}" /> <!--is指定使用模版的名称-->

引用wxss模版:

在使用模版文件对应的wxss文件中输入以下表达式即可

@import "../stars/stars-template.wxss";

数据装换:

我看到在使用模版wxml文件时有个data=“{{stars:stars,score:average}}”属性和数据,表示指定模版的数据,我们一般从后台获取的评分数据一般都是一个数字,比如:3.5,4,5等等,我们需要把这些数字转换成五个等级数组,决定评分星星显示什么图片,这里我们用1表示显示高亮的,0表示灰色星星,我们也可以在一个2表示半颗高亮的星星表示0.5的评分:

function convertToStarsArray(stars) {
 var num = stars.toString().substring(0, 1);
 var array = [];
 for (var i = 1; i <= 5; i++) {
  if (i < num) {
   array.push(1);
  } else {
   array.push(0);
  }
 }
 return array;
}

案例wxml代码:

<import src="stars/stars-template.wxml" />
<view style='margin:100rpx'>
 <template is="starsTemplate" data="{{stars:stars,score:average}}" />
</view>

到这里基本结束了,我们这评分转换成我们需要的评分数组,在使用模版的地方传入数据即可。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们