微信小程序开发入门(连载)—— Hello World

上一篇:微信小程序开发入门(连载)—— 微信公众平台配置


3.1 微信开发者工具

前往 开发者工具下载页面 (https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html),根据自己的操作系统下载对应的安装包进行安装,有关开发者工具更详细的介绍可以查看 《开发者工具介绍》(https://developers.weixin.qq.com/miniprogram/dev/devtools/devtools.html)

打开小程序开发者工具,用微信扫码登录开发者工具,准备开发你的第一个小程序吧!

enter image description here

3.2 第一行代码

新建项目选择小程序项目,选择代码存放的硬盘路径,填入刚刚申请到的小程序的 AppID,给你的项目起一个好听的名字,最后,点击 “创建项目” (注意: 你要选择一个空的目录才会有这个选项),点击确定,你就得到了你的第一个小程序了,点击顶部菜单编译就可以在微信开发者工具中预览你的第一个小程序。

enter image description here

这是开发者工具自动生成HelloWorld演示程序,接下来我们来看一下它的主要代码并预览一下这个小程序的效果。

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>

有没有很熟悉?貌似html?

可以这样理解,在wxml中的view可以理解为html中的div,代码中的“wx:if”用来做逻辑判断,如果wx:if内的值成立就渲染并显示,否则不进行渲染显示。

你可以像写网页一样写小程序,只不过换成了wxml的标签规范,多写写也就熟悉了。

index.js

//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

js还是那个js,原来怎样写现在还怎样写。你可以多了解一下微信小程序的几个关键的生命周期函数。

下图说明了页面 Page 实例的生命周期。

enter image description here

预览效果

enter image description here

点击工具上的编译按钮,可以在工具的左侧模拟器界面看到这个小程序的表现,也可以点击预览按钮,通过微信的扫一扫在手机上体验你的第一个小程序。

通过这个章节,你已经成功创建了你的第一个小程序,并且在微信客户端上体验到它流畅的表现。


电子邮箱:[email protected]
简介:中华人民共和国公民,中国共青团员,CSDN博客专家,秦淮区疾控中心托管社会公益组织指南针工作室志愿者,在校大学生,参与过微信小程序《约车吗》、《指南针微公益》、《智慧庆云禅寺》的开发。


发布了103 篇原创文章 · 获赞 205 · 访问量 62万+

猜你喜欢

转载自blog.csdn.net/yuanxiang01/article/details/94822433