设为首页 加入收藏

TOP

【微信小程序】开发实战 之 「视图层」WXML & WXSS 全解析(三)
2019-09-17 19:09:33 】 浏览:108
Tags:程序 开发 实战 WXML WXSS 解析
y:[
1,2,3,4] }, switch: function(e){ const length = this.data.objectArray.length for(let i=0; i < length; i++){ const x = Math.floor(Math.random() * length) const y = Math.floor(Math.random() * length) const temp = this.data.objectArray[x] this.data.objectArray[x] = this.data.objectArray[y] this.data.objectArray[y] = temp } this.setData({ objectArray:this.data.objectArray }) }, addToFront:function(e){ const length = this.data.objectArray.length this.data.objectArray = [{id:length, unique: 'unique_'+length}].concat(this.data.objectArray) this.setData({objectArray:this.data.objectArray}) }, addNumberToFront:function(e){ this.data.numberArray = [this.data.numberArray.length + 1].concat(this.data.numberArray) this.setData({ numberArray:this.data.numberArray }) } })

 (可以小程序开发工具中预览效果,注意将wxml片段和j片段分别保存在.wxml文件和.js文件中)

页面布局模板

WXML支持使用模版(template)。可以在模版中定义代码片段,然后在别的地方引用。

  • 定义模版

定义模版时,使用name属性为模版命名。 在<template />标签内定义模版代码片段,下面是一段电影列表页面显示电影评级星数的模版:

<template name="starsTemplate">
  <view class="stars-container">
    <view class="stars">
    <block wx:for = "{{stars}}" wx:for-item="i">
      <image wx:if="{{i}}" src="/images/icon/star.png"></image>
      <image wx:else src="/images/icon/none-star.png"></image>
    </block>
    </view>
    <text class="star-score">{{score}}</text>
  </view>
</template>
  •  使用模版

使用is属性声明需要使用的模版还需要将模版所需要的data传入,例如:

<!--wxml-->
      <template is="starsTemplate" data="{{stars:stars,score:average}}"/>

 is 属性还可以借助 Mustache 语法,来动态决定具体需要渲染哪个模版:

<template name="fir">
    <view> first </view> 
</template>
<template name="sec">
    <view> second </view> 
</template>

<block wx:for="{{[1,2,3,4,5]}}">
    <template is="{{item % 2 == 0 ? 'fir' : 'sec'}}" />
</block>

模版拥有自己的作用域,它只能使用data传入的数据。

文件引用

WXML提供两种文件引用的方式:import 和 include。

  • import

import 可以在当前文件中使用目标文件定义的template,例如,在 item.wxml 中定义了一个叫 item 的 template:

<!-- item.wxml-- >
<template name = "item">
  <view>{{text}}</view>
</template>

在index.wxml中引用item.wxml,就可以使用item模版:

<import src = "item.wxml" />
<template is = "item" data = "{{text: 'forbar'}}" />

 

import是有作用域概念的,只会引用目标文件中定义的template,而不能引用目标文件嵌套import的template。比如,C import B , B import A,在C中可以使用B定义的template,在B中可以使用A定义的template,但是C不能使用A中定义的template。

  • include

include可将目标文件除模版代码(<template />)块的所有代码引入,相当于拷贝到include位置。

<!-- index.wxml -->
<include src = "header.wxml" />
<view> body </view> 

<include src = "footer.wxml" />

<!-- header.wxml -->
<view> header </view> 

<!-- footer.wxml -->
<view> footer </view> 

事件绑定

事件的定义

事件是视图层到逻辑层的通信方式,可以将用户的行为反馈到逻辑层进行处理。事件绑定到组件上,当触发事件时,就会执行逻辑层中对应的事件处理函数。事件对象可以携带额外的信息,如id、dataset、touches。

事件的使用

小程序与用户的交互

首页 上一页 1 2 3 4 5 6 下一页 尾页 3/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇微信小程序-强制手机端更新 下一篇深入V8引擎-初始化默认Platform

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目