• 技术文章 >微信小程序 >小程序开发

    八分钟带你入门微信小程序开发

    烟雨青岚烟雨青岚2020-06-29 11:13:12转载1674

    注册微信小程序

    如果你还没有微信公众平台的账号,请先进入微信公众平台首页,点击 “立即注册” 按钮进行注册。注册的账号类型可以是订阅号、服务号、小程序以及企业微信,我们选择 “小程序” 即可。

    接着填写账号信息,需要注意的是,填写的邮箱必须是未被微信公众平台注册、未被个人微信号绑定的邮箱,而且每个邮箱仅能申请一个小程序。

    激活邮箱之后,选择主体类型为 “个人类型”,并按要求登记主体信息。主体信息提交后不可修改,该主体将成为你使用微信公众平台各项服务和功能的唯一法律主体与缔约主体,在后续开通其他业务功能时不得变更或修改。

    1322c02cc307040e086720d9787f577.png

    一切 OK 就可以直接进入小程序的管理平台了。如果直接跳转失败,也可以从微信公众平台上手动登录。填写小程序的基本信息,包括名称、图标、描述等。提交成功之后,再添加开发者。开发者默认为管理员,我们也可以从这里新增绑定开发者,这是管理员才有权限的操作。

    然后在左侧导航栏点击 “设置”,找到开发设置,获得小程序的 AppID。

    微信开发者工具

    下载微信web开发者工具,根据自己的操作系统下载对应的安装包进行安装即可。

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

    第一个小程序

    新建项目

    打开开发者工具,选择 “小程序项目”,点击右下角的 “+” 新建项目。

    选择一个空的文件夹作为项目目录,填入刚刚的 AppID,再填写一个项目名称,比如我这里叫做 GoZeroWaster。点击 “确定” 进入工具主界面。

    项目目录结构

    微信小程序的基本文件构造和项目目录结构说明如下:

        .
        ├── app.js     # 小程序的逻辑文件
        ├── app.json   # 小程序的配置文件
        ├── app.wxss   # 全局公共样式文件
        ├── pages      # 存放小程序的各个页面
        │   ├── index  # index页面
        │   │   ├── index.js     # 页面逻辑
        │   │   ├── index.wxml   # 页面结构
        │   │   └── index.wxss   # 页面样式表
        │   └── logs   # logs页面
        │       ├── logs.js      # 页面逻辑
        │       ├── logs.json    # 页面配置
        │       ├── logs.wxml    # 页面结构
        │       └── logs.wxss    # 页面样式表
        ├── project.config.json
        └── utils
            └── util.js

    根目录下有3个文件:app.js、app.json、app.wxss,小程序必须有这3个描述 APP 的文件,并放在根目录下。这3个是应用程序级别的文件,与之平行的还有一个 pages 文件夹,用来存放小程序的各个页面。

    我们可以和 web 前端开发技术做个类比:

    目标成果

    我们先来看看最终的目标和成果,很简单,一共两页:

    bea82ba1b2b585a45f4052abd15f9af.png

    (为了让广大程序员也能保护环境和热爱生活,我特意选了 “零垃圾生活” 主题来做 Demo)

    步骤分解

    Demo 代码下载:https://gitee.com/luhuadong/Web_Learning/tree/master/WeChat/GoZeroWaster

    分解目标成果:

    1. 个人中心
    2. 生活指南
    3. 模拟弹窗
    4. 预览图片

    页头页尾

    在目标成果预览中我们看到,两个页面都有共同的部分 —— 页头和页尾。所以在构建页面内容之前,我们先把页头和页尾处理好。我们很容易猜到,这两部分属于小程序的全局配置,因此需要修改 app.json 文件。

    最初的内容如下:

        {
            "pages":[
                "pages/index/index",
                "pages/logs/logs"
            ],
            "window":{
                "backgroundTextStyle": "light",
                "navigationBarBackgroundColor": "#fff",
                "navigationBarTitleText": "WeChat",
                "navigationBarTextStyle": "balack"
            }
        }

    pages 属性用来设置页面路径,它是一个数组,每一项都是字符串来指定小程序由哪些页面组成。数组的第一项代表小程序的初始页面。小程序中新增或减少页面,都需要对 pages 数组进行修改。

    window 属性用于设置小程序的状态栏、导航条、标题、窗口背景色。

    我们把页头的标题和颜色修改一下,页尾部分我们做一个 tab 栏来切换页面,这个属性叫做 tabBar,代码如下:

    {
      "pages":[
        "pages/index/index",
        "pages/logs/logs"
      ],
      "window":{
        "backgroundTextStyle":"light",
        "navigationBarBackgroundColor": "#2f2f8f",
        "navigationBarTitleText": "GoZeroWaste",
        "navigationBarTextStyle":"white"
      },
      "tabBar":{
        "color": "#bfc1ab",
        "selectedColor": "#13b11c",
        "backgroundColor": "#1f1f4f",
        "list": [
          {
            "pagePath": "pages/index/index",
            "iconPath": "image/icon_component.png",
            "selectedIconPath": "image/icon_component_HL.png",
            "text": "个人中心"
          },
          {
            "pagePath": "pages/details/details",
            "iconPath": "image/icon_API.png",
            "selectedIconPath": "image/icon_API_HL.png",
            "text": "生活指南"
          }
        ]
      }}

    (所用到的图片放在项目的 image 目录,你也可以使用自己的图片)

    这里用到几个 tabBar 的属性是 color、selectedColor、backgroundColor 和 list,list 是一个数组,主要用于设定导航的路径。

    CTRL + S 保存之后,模拟器就会自动刷新,马上可以看到效果。

    个人中心

    97d3112488053dcf9f50e4cc71cf6c3.png

    简单起见,我们就在 pages/index 目录下实现 “个人中心” 页面好了。双击打开 index.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}}" background-size="cover"></image>
              <text class="userinfo-nickname">{{userInfo.nickName}}</text>
            </block>
          </view>
          <view class="usermotto">
            <text class="user-motto">{{motto}}</text>
          </view>
        </view>

    这里已经有一些代码了,虽然现在可能还看不懂,但我们知道,这就是现在页面的源代码。我们把 “Hello World” 部分注释掉,增加我们希望显示的内容:

    <!--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}}" background-size="cover"></image>
          <text class="userinfo-nickname">{{userInfo.nickName}}</text>
        </block>
      </view>
       <!-- <view class="usermotto">
        <text class="user-motto">{{motto}}</text>
      </view>  -->
      <view class="ID_Badge">
        <view>
          <text class="ID_info">{{company}}</text>
        </view>
        <view>
          <text class='ID_info'>{{position}}</text>
        </view>
        <view>
          <text class='ID_info'>{{lesson}}</text>
        </view>
      </view></view>

    这里分别使用 {{company}}{{position}}{{lesson}} 作为占位符,用法类似于 Django 的模板语言。当然也可以直接用相应的字符来替换它,只不过我们想沿用 {{motto}} 的做法,让你知道在哪里修改这些数据。没错,就是在 index.js 文件:

    Page({
      data: {
        motto: 'Hello World',
        company: "GoZeroWaste",
        lesson: "21天零垃圾生活指南",
        position: "垃圾魔法师",
        /* ... */
      }

    wxml 文件中的 <view> 组件类似于网页开发中的 <p>,而 <text> 组件是用来写文本的,需要注意的是 <text/> 组件内只支持 <text/> 嵌套。当然,可用用 <image> 插入图片,图片要保存到 image 目录,否则在测试的时候是无法上传的。

        <view class="ID_Badge">
            <!-- 省略 -->
            <view>
              <text class='ID_info'>{{lesson}}</text>
            </view>
            <view>
              <image class='pic' mode='widthFix' src='../../image/GoZeroWaste.jpg'></image>
            </view>
          </view>

    mode=‘widthFix’ 表示以宽度不变,高度自动变化,保持原图宽高比不变的方式进行缩放以适应屏幕大小。

    接下来还需要修改 index.wxss 文件来设置样式:

    /**index.wxss**/.userinfo {
      display: flex;
      flex-direction: column;
      align-items: center;}.userinfo-avatar {
      width: 128rpx;
      height: 128rpx;
      margin: 20rpx;
      border-radius: 50%;}.userinfo-nickname {
      color: #aaa;}.usermotto {
      margin-top: 200px;}.ID_Badge {
      padding-top: 20rpx;
      color: blue;}.ID_info {
      display: flex;
      flex-direction: column;
      align-items: center;}.pics {
      width: 400rpx;}

    保存刷新,“个人中心” 页面就完成了。

    生活指南

    9116fa18fd93cc5e55dd93f90212482.png

    原来的项目中 pages 目录下只有 index 和 logs 两个目录,因此我们还需要为第二个页面创建一个目录。

    创建页面有两种方法:

    建议采用第二种方法,修改 app.json 文件:

        {
          "pages":[
            "pages/index/index",
            "pages/logs/logs",
            "pages/details/details"
          ]

    保存刷新之后就会发现,目录结构里自动创建了这一页。对应的,也要修改 app.json 中的 tabBar 的链接(实际上我们已经做了):

        	{
                "pagePath": "pages/details/details",
                "iconPath": "image/icon_API.png",
                "selectedIconPath": "image/icon_API_HL.png",
                "text": "生活指南"
            }

    然后修改 details.wxml 设置这一页的标题:

        <!--pages/details/details.wxml-->
        <view>
          <view class='title'>
            <text>21天零垃圾生活指南</text>
          </view>
        </view>

    修改 details.wxss 设置样式:

        /* pages/details/details.wxss */
        .title {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-top: 40rpx;
          margin-bottom: 40rpx;
          font-size: 40rpx;
        }

    这个页面是一个列表展示的页面,我们先在 details.js 文件中准备好数据:

    // pages/details/details.jsPage({
    
      /**
       * 页面的初始数据
       */
      data: {
        showModalStatus: false,
        list: [
          {
            id: 0,
            name : "写一篇《垃圾日记》",
            introduce: "零垃圾并不是一项宏大的工程,而是由日常生活中一个个小小的习惯和选择组成的。最难的,是迈出第一步。",
            src: '../../image/day01.jpg',
            showModalStatus: false,
            catalog: [
              { section: "1. xxx" },
              { section: "2. xxx" },
              { section: "3. xxx" },
              { section: "4. xxx" },
            ]
          },
          {
            id: 1,
            name: "带上自己的购物袋",
            introduce: "在我们家,当时垃圾桶里最多的就是塑料袋,而这些袋子跟着我回家后,都几乎难逃被丢进垃圾桶的命运。",
            src: '../../image/day02.jpg',
            showModalStatus: false,
            catalog: [
              { section: "1. xxx" },
              { section: "2. xxx" },
              { section: "3. xxx" },
              { section: "4. xxx" },
            ]
          },
          /* 省略 */
        ]
      }

    接下来我们要使用列表渲染(wx:for)的方法将这些数据绑定一个数组,并在页面上重复渲染。修改 details.wxml 文件:

          <view>
            <view wx:for="{{list}}" wx:key="id" >
              <view class="lesson" id="{{item.id}}">
                <image class="lessonPic" mode='aspectFit' src="{{item.src}}"></image>
                <view class="lessonName">{{item.name}}</view>
                <view class="lessonIntroduce">{{item.introduce}}</view>
              </view>
            </view>
          </view>

    默认数组的当前项的下标变量名默认为 index,数组当前项的变量名默认为 item。

    修改 details.wxss 文件添加样式:

        .lesson {
          height: 190rpx;
          padding-left: 20rpx;
        }
        
        .lessonPic {
          position: absolute;
          height: 150rpx;
          width: 150rpx;
        }
        
        .lessonName {
          position: absolute;
          margin-left: 220rpx;
          font-size: 35rpx;
        }
        
        .lessonIntroduce {
          position: absolute;
          margin-left: 220rpx;
          margin-top: 60rpx;
          margin-right: 20rpx;
          color: rgb(185, 161, 161);
          font-size: 28rpx;
        }

    好啦,第二个页面也完成了。

    模拟弹窗

    5cb5055cbeef43e31622a0cf9ae779c.png

    接下来我们要在 “生活指南” 页面模拟一个弹窗的效果,正常的时候不显示,只有在点击的时候才出现,摁下面的 “确定” 就会消失。

    完了实现这个功能,我们要在组件中绑定一个事件处理函数 bindtap,点击该组件的时候,小程序会在该页面对应的 Page 中找到相应的事件处理函数。

    我们先在 details.js 中为每一列数据里引入一个 boolean 变量 showModalStatus 来描述对应的弹窗状态,并且初始值为 false,表示不显示。同时外层也增加一个初始值为 false 的 showModalStatus 变量实现遮罩效果。如下:

           data: {
            showModalStatus: false,
            list: [
              {
                id: 0,
                name : "写一篇《垃圾日记》",
                introduce: "零垃圾并不是一项宏大的工程,而是由日常生活中一个个小小的习惯和选择组成的。最难的,是迈出第一步。",
                src: '../../image/day01.jpg',
                showModalStatus: false,
                catalog: [
                  { section: "1. xxx" },
                  { section: "2. xxx" },
                  { section: "3. xxx" },
                  { section: "4. xxx" },
                ]
              }

    然后在 details.wxml 中插入弹窗,并用条件渲染(wx:if)来判断是否渲染(显示)弹窗。同时为每一个 item 添加 data-statu 来表示弹窗的状态。如下:

      <view>
        <view wx:for="{{list}}" wx:key="id" >
          <view class="lesson" bindtap='powerDrawer' data-statu='open' id="{{item.id}}">
            <image class="lessonPic" mode='aspectFit' src="{{item.src}}"></image>
            <view class="lessonName">{{item.name}}</view>
            <view class="lessonIntroduce">{{item.introduce}}</view>
          </view>
            
          <!-- 弹窗 -->
          <view class='drawer_box' wx:if='{{item.showModalStatus}}' id='{{item.id}}'>
            <view class="title">{{item.name}}</view>
            <view class='drawer_content'>
              <view class='title' wx:for='{{item.catalog}}' wx:for-item='catalog' wx:key='id'>
                {{catalog.section}}          </view>
            </view>
            <!-- 确定按钮 -->
            <view class='btn_ok' bindtap='powerDrawer' data-statu='close' id='{{item.id}}'>确定</view>
          </view>
        </view>
          
        <!-- 遮罩层 -->
        <view class='drawer_screen' data-statu='close' wx:if='{{showModalStatus}}'></view>
      </view>

    在 details.js 添加 powerDrawer 事件处理,包括显示和关闭事件:

          powerDrawer: function (e) {
            console.log("clicked");
        
            var currentStatu = e.currentTarget.dataset.statu;
            var index = e.currentTarget.id;
        
            // 关闭
            if (currentStatu == 'close') {
              this.data.list[index].showModalStatus = false;
              this.setData({
                showModalStatus: false,
                list: this.data.list,
              });
            }
        
            // 显示
            if (currentStatu == 'open') {
              this.data.list[index].showModalStatus = true;
              this.setData({
                showModalStatus: true,
                list: this.data.list,
              });
            }
          },

    最后在 details.wxss 设置一下弹窗和遮罩层的样式:

        .drawer_box {
          width: 650rpx;
          overflow: hidden;
          position: fixed;
          top: 50%;
          z-index: 1001;
          background: #FAFAFA;
          margin: -150px 50rpx 0 50rpx;
        }
        
        .drawer_content {
          border-top: 1.5px solid #E8E8EA;
          height: 210px;
          overflow-y: scroll; /* 超出父盒子高度可滚动 */
        }
        
        .btn_ok {
          padding: 10px;
          font: 20px "microsoft yahei";
          text-align: center;
          border-top: 1.5px solid #E8E8EA;
          color: #3CC51F;
        }
        
        .drawer_screen {
          width: 100%;
          height: 100%;
          position: fixed;
          top: 0;
          left: 0;
          z-index: 1000;
          background: black;
          opacity: 0.5;
          overflow: hidden;
        }

    OK,模拟弹窗也实现了。

    预览图片

    752fced6b3d056e4a61c49cc87d197b.png

    最后一步就是在第一个页面实现图片预览和图片保存的功能,在 index.wxml 中为图片添加一个点击事件 previewImage。

        <image class='pic' mode='widthFix' src='../../image/GoZeroWaste.jpg' bindtap='previewImage'></image>

    在 index.js 中添加 imgalist 项(我们直接把公众号的二维码图片上传到 CSDN 的图片服务器了),并且实现 previewImage 事件处理。如下:

        Page({
          data: {
            motto: 'Hello World',
            company: "GoZeroWaste",
            lesson: "21天零垃圾生活指南",
            position: "垃圾魔法师",
            imgalist: ['https://img-blog.csdnimg.cn/20190109104518898.jpg'],
            userInfo: {},
            hasUserInfo: false,
            canIUse: wx.canIUse('button.open-type.getUserInfo')
          },
          previewImage: function (e) {
            wx.previewImage({
              current: this.data.imgalist,  // 当前显示图片的http链接
              urls: this.data.imgalist      // 需要预览的图片http链接列表
            })
          },

    大功告成,点击开发者工具中的 “预览”,使用微信扫描生成的二维码即可在手机端查看。

    教程就到这里,希望大家可以对微信小程序有所了解。

    本文转自:https://luhuadong.blog.csdn.net/article/details/86181251

    推荐教程:《微信小程序

    以上就是八分钟带你入门微信小程序开发的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除
    专题推荐:微信小程序开发
    上一篇:小程序new Date()方法失效怎么办 下一篇:小程序页面间传递数据的方式
    大前端线上培训班

    相关文章推荐

    • 小程序开发经验的总结• 微信小程序开发中var that =this的基本用法• 微信小程序开发初次体验• 新手必备的微信小程序开发指南

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网