微信小程序开发学习------(分析视图程序)

根据https://blog.csdn.net/weixin_30363263/article/details/89449966我们搭好了微信小程序环境。

实现了能把该小程序的体验版以二维码的方式发送给其他朋友使用。

接下来研究使用微信开发者工具自动生成的这个小程序的实现文件。

本文以小程序的视图设计为主,就是下图所示pages/index目录里的index.wxml文件。

微信小程序的wxml类似网页开发,也可把wxml类比成JSP文件。

wxml源代码:

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo"    bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

下面逐一解释每行代码。

第二行:<view class="container"> 声明了一个视图元素,css类型为container。

这个container类是微信小程序自带的,如果删除,小程序视图位置会改变,大家可以自己试一下。

扫描二维码关注公众号,回复: 9220418 查看本文章

第三行: <view class="userinfo"> view元素可以嵌套,相当于原生HTML里的div元素。类似于css进行装饰的,定义了另一个view元素,css类为userinfo。这个css类不是微信提供的,而是我们自己开发的,位于文件index.wxss里:

第四行:<button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="jerry_getUserInfo"> 获取头像昵称 </button>

表示定义了一个按钮,标签为“获取头像昵称”。按钮仅当表达式!hasUserInfo && canIUse为true时才显示。

button是微信小程序框架提供的组件,组件是视图层的基本组成单元,自带一些功能与微信风格的样式。

注意这里的button标签并不是HTML原生的标签。

在微信官网上可以查询组件的API:

https://developers.weixin.qq.com/miniprogram/dev/component/

下面这两个属性的含义:

open-type="getUserInfo": 点了这个按钮之后,会自动取当前点击了该按钮的微信用户的明细数据

bindgetuserinfo="jerry_getUserInfo": 当用户数据成功取回来之后,执行我们自己开发的回调函数jerry_getUserInfo, 该函数定义在小程序index/index.js里。

第五行到第八行:

<block wx:else>

<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>

<text class="userinfo-nickname">{{userInfo.nickName}}</text>

</block>

定义了一个block区域,有两个UI元素组成:image和text。

对image元素,bindtap="bindViewTap", 意思是一旦点击,执行我们在index.js里实现的事件处理函数bindViewTap。

class="userinfo-avatar": userinfo-avatar也是我们在wxss里自定义的css类。

src="{{userInfo.avatarUrl}}": 该image的src属性绑定到数据模型userInfo的字段avatarUrl上。数据类型userInfo是index.js里创建的,绑定到当前的视图上。

而另一个文本元素text显示的文本绑定到userInfo.nickName上。

第11行:<text class="user-motto">{{motto}}</text>

纯文本元素,显示的文本绑定到数据模型motto上。这个模型字段motto硬编码成Hello World,所以我们最后在小程序上看到显示的“Hello World"。

发布了290 篇原创文章 · 获赞 524 · 访问量 60万+

猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/89710591