小程序常用基础语法精选

最近在看小程序文档整理下简单的语法场景

<!--index.wxml-->
<!-- 模板导入 -->
<!-- 于此对应的还有 include 可以将目标文件除了 <template/> <wxs/> 外的整个代码引入,相当于是拷贝到 include 位置 -->
<import src="../temp.wxml" />
<view class="container">
    <view>首页</view>

  <!-- 花括号和引号之间如果有空格,将最终被解析成为字符串 -->
    <view>{{deviceInfo.system}}</view>
    <van-toast  />
    <van-button type="primary" bind:click="goNext">跳转</van-button>

  <!-- 组件属性 注意如果是:关键字(需要在双引号之内) 特别注意:不要直接写 checked="false",其计算结果是一个字符串,转成 boolean 类型后代表真值-->
  <view  data- bindtap='getCustomProperties'>点击我获取自定义属性</view>
  <checkbox checked="{{false}}"> </checkbox>
  <checkbox checked="{{true}}"> </checkbox>
  <!-- 三元运算 -->
  <view hidden="{{flag ? true : false}}"> Hidden </view>
  <!-- 加减运算 3+5+d 4+d-->
  <view> {{a + b}} + {{c}} + d </view>
  <view> {{2 + 2}} + d </view>

    <!-- 双层循环使用 wx:for-item 可以指定数组当前元素的变量名, 使用 wx:for-index 可以指定数组当前下标的变量名 -->
    <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i" wx:key="*this">
        <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="j" wx:key="*this">
            <text> {{i}} * {{j}} = {{i * j}}</text>
        </view>
    </view>
  <!-- wx:for 渲染一个包含多节点的结构块 -->
  <!-- 如不提供 wx:key(建议每个wx:for写上wx:key),会报一个 warning *this 代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字 -->
  <block wx:for="{{[4, 5, 6]}}" wx:key="*this">
    <view> {{index}}---{{item}}--节点 </view>
  </block>

    <!-- 模板语法 -->
    <template is="a" data="{{...item}}" />
    <template is="b" data="{{...item}}" />

    <!-- wx:if 条件渲染语法的使用 -->
    <view wx:if="{{5 > 6}}"> 1 </view>
    <view wx:elif="{{5 > 2}}"> 5 </view>
    <view wx:else> 3 </view>
</view>
  data: {
    id: 0,
    flag: true,
    a: 1,
    b:2,
    c:5,
    // 模板数据
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    },
    deviceInfo: {},
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  getCustomProperties(e){
    console.log(e.currentTarget.id,'组件属性(比如)
    console.log(e.currentTarget.dataset.id,'自定义属性(data-xxx)获取')
  },
<!--pages/temp.wxml-->
<!-- 模板a name字段区分模板 -->
<template name="a">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

<!-- 模板b name字段区分模板 -->
<template name="b">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

页面传参 取参

  goNext(){
    wx.navigateTo({
      url: "../test/test?
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options,'options.xx就可以获取上一个页面带过来的参数')
  },

原创未经允许不得转载!!!转载请注明出处~谢谢合作;