微信小程序学习笔记-2.1 wx.for 和 wx.if 的使用

wx:for 和 wx:if 可以很方便的创建 wxml 元素

本例将用 swiper 内对象的创建来展示其效果

1. 前期准备

首先创建目录和工程文件 main

main.js 中,创建静态 list

data: {
    testList: [
      {
        name: "测试1",
        element: "测试1的相关内容",
        isHighLighted: true,
        id: 1
      },
      {
        name: "测试2",
        element: "测试2的相关内容",
        isHighLighted: false,
        id: 2
      }],
     
  },

在 main.wxml 中简单的创建一个 swiper 对象 使用相关参数方便观察

<swiper indicator-dots='true' previous-margin='50rpx' next-margin='50rpx'>

三个参数意思比较明显,在此不作详细解释

2.创建单个 swiper-item(使用wx:if)
 <swiper-item>
    <view class='container'>
      <text>标题:{{testList[0].name}}</text>
      <text>元素:{{testList[0].element}}</text>
      <text style="color:red" wx:if="{{testList[0].isHighLighted}}">推荐</text>
    </view>
  </swiper-item>

数据绑定获取 list 中第一个元素的全部属性并放置在 swiper-item 下的 view 元素中

wx:if 后的参数结果如果是 true ,则渲染该条 否则就不渲染

这个和 hidden 不一样,hidden 渲染但是不显示

效果如上

3.遍历创建 items(wx:for 的使用)

wx:for 后直接跟一个可迭代对象

自动产生了 item 和 index 两个属性 item 效果相当于每一个正在被遍历的元素

 <swiper-item wx:for='{{testList}}'>
    <view class='container'>
      <text>标题:{{item.name}}</text>
      <text>元素:{{item.element}}</text>
      <text style="color:red" wx:if="{{item.isHighLighted}}">推荐</text>
    </view>
  </swiper-item>

写法如上,结果如下


当然,你也可以定义固定的初始 swiper 页面

在 swiper 中添加 current="" 参数即可






猜你喜欢

转载自blog.csdn.net/weixin_42271658/article/details/80459740