微信小程序初体验--玩安卓小程序

1,097 阅读6分钟

前言

     这是一个基础版本,做的有些糙,欢迎给出意见及建议,后续会继续完善

        关于微信小程序开发前期的准备工作及一些介绍此处就不再赘述,可以去阅读官方文档

        小程序的api接口都来自于玩Android 开放API

        小程序的图标都来自于Iconfont-阿里巴巴矢量图标库

        关于小程序的UI,有参考其他app或小程序的界面

        对了~先来放一张小程序的主页

小程序首页.png

本文的代码是关联在一个测试账号下的,但是本人上架了一个相同的个人版小程序,欢迎扫码体验,后期还有功能会继续完善,鉴于个人版本无法使用web-view,点击之后很多都是复制对应文章的链接。

小程序二维码.jpg

一、创建页面

        说是创建页面,但是这里只能创建最外层的大页面,毕竟小程序是VM模式,详细页面显示还需要请求的数据回来之后在wxml文件里面去解析         由上图可以看见有五个大的TAB页面,所以我们需要在小程序pages目录下创建五个类似于下图的五个文件夹

     分别对应五个不同的页面,文件夹里面的四个文件,稍后分解。

       注意:每次创建完一个新的页面需要在app.json文件中进行注册,类似于安卓创建一个新的activity需要去AndroidManifest.xml中去注册

        到这里页面应该可以展示了,但是只能展示home一个页面,还需要在app.json中加入以下代码才能像上面首页图中一样以五个TAB的方式呈现

 "tabBar": {
    "selectedColor": "#1296db",
    "color": "#2c2c2c",
    "backgroundColor": "#fff",
    "borderStyle": "black",
    "list": [
      {
        "pagePath": "pages/home/home",
        "text": "首页",
        "iconPath": "pages/images/home_normal.png",
        "selectedIconPath": "pages/images/home_select.png"
      },
      {
        "pagePath": "pages/system/system",
        "text": "体系",
        "iconPath": "pages/images/system_normal.png",
        "selectedIconPath": "pages/images/system_select.png"
      },
      {
        "pagePath": "pages/hot/hot",
        "text": "热搜",
        "iconPath": "pages/images/hot_normal.png",
        "selectedIconPath": "pages/images/hot_select.png"
      },
      {
        "pagePath": "pages/project/project",
        "text": "项目",
        "iconPath": "pages/images/project_normal.png",
        "selectedIconPath": "pages/images/project_select.png"
      },
      {
        "pagePath": "pages/mine/mine",
        "text": "我的",
        "iconPath": "pages/images/mine_normal.png",
        "selectedIconPath": "pages/images/mine_select.png"
      }
    ]
  },

-----------------以下操作全部以首页home页面的实现为例来讲解-----------------

二、请求数据

鉴于api接口都是以http打头,但是微信小程序规定是所有请求地址都需要是https的,方便测试可以勾选下图方框中的选项。

###注意:这样只能测试效果使用,如需上线或者上传体验或者真机调试都不能勾选该选项,而是要去管理平台去申请合法域名。 话不多说了,请求数据了~~ 请求数据的操作是在home.js文件里面完成的,调用wx.request方法直接发起请求。

 //加载数据
  loadData() {
    var that = this
    wx.request({ //请求文章列表数据
      url: "http://www.wanandroid.com/article/list/" + this.data.pageNum + "/json",
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res.data)
        if (res.data.errorCode == 0) {
          var responseList = [];
          // console.log('success')
          that.data.isFirstRequest ? responseList = res.data.data.datas : responseList = that.data.articles.concat(res.data.data.datas)
          that.setData({
            articles: responseList
          })
          wx.hideLoading();
          // 隐藏导航栏加载框
          wx.hideNavigationBarLoading();
          // 停止下拉动作
          wx.stopPullDownRefresh();
          // that.setData({
          //   articles: res.data.data.datas
          // })
        } else {
          console.log('获取失败');
        }
      }
    })
  },

贴出home.js全部代码

home.js

var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isFirstRequest: true,
    BannerData: [],
    swiperCurrent: 0,
    articles: [],
    pageNum: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    wx.request({ //请求banner的数据
      url: app.globalData.HomeBannerUrl, //这里是在app.js的globalData中声明的,如同java中的全局变量
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res.data)
        if (res.data.errorCode == 0) {
          that.setData({
            BannerData: res.data.data
          })
        } else {
          console.log('获取失败');
        }
      }
    })

    this.setData({
        isFirstRequest: true
      }),
      this.loadData()
  },
  //加载数据
  loadData() {
    var that = this
    wx.request({ //请求banner下面的文章列表数据
      url: "http://www.wanandroid.com/article/list/" + this.data.pageNum + "/json",
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res.data)
        if (res.data.errorCode == 0) {
          var responseList = [];
          // console.log('success')
          that.data.isFirstRequest ? responseList = res.data.data.datas : responseList = that.data.articles.concat(res.data.data.datas)
          that.setData({
            articles: responseList
          })
          wx.hideLoading();
          // 隐藏导航栏加载框
          wx.hideNavigationBarLoading();
          // 停止下拉动作
          wx.stopPullDownRefresh();
          // that.setData({
          //   articles: res.data.data.datas
          // })
        } else {
          console.log('获取失败');
        }
      }
    })
  },
  //轮播图的切换事件
  swiperChange: function(e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  //轮播图点击事件
  swipclick: function(e) {
    console.log(e.currentTarget.dataset)
    app.globalData.webUrl = e.currentTarget.dataset.data.url
    // app.globalData.fromWhere='homeBanner'
    wx.navigateTo({
      url: '../web/web'
    });
  },
  //首页列表点击事件
  articleClick: function(e) {
    console.log(e.currentTarget.dataset)
    app.globalData.webUrl = e.currentTarget.dataset.data.link
    // app.globalData.fromWhere = 'homearticles'
    wx.navigateTo({
      url: '../web/web'
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {//下拉刷新
    var that = this;
    wx.showNavigationBarLoading();
    that.setData({
        pageNum: 0,
        isFirstRequest: true
      }),
      that.loadData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {//上拉加载更多
    var that = this;
    wx.showLoading({
      title: '玩命加载中',
    })

    that.setData({
        pageNum: that.data.pageNum + 1, //页码增加请求更多
        isFirstRequest: false
      }),
      that.loadData()
  },
})

     请求数据是很简单的,就几行代码就可以完成,复杂的是数据回来如何显示的问题。

三、解析数据+详细页面展示

     前面请求数据已经涉及到了home.js,下面的操作将涉及home.wxml和home.wxss

     VM模式,数据在home.js里面请求,然后在home.wxml中来解析及展示,至于home.wxss就是辅助home.wxml展示的,其实就类似于html+css。 #home.wxml

<scroll-view>
  <view class="swiper-container">
    <swiper autoplay="auto" interval="3000" duration="500" current="{{swiperCurrent}}" bindchange="swiperChange" class="swiper">
      <block wx:for="{{BannerData}}" wx:key="unique">
        <swiper-item data-id="{{item.id}}" data-url="{{item.url}}">
          <image src="{{item.imagePath}}" class="img" bindtap='swipclick' data-data="{{item}}"></image>
        </swiper-item>
      </block>
    </swiper>
    <view class="dots">
      <block wx:for="{{BannerData}}" wx:key="unique">
        <view class="dot{{index == swiperCurrent ? ' active' : ''}}"></view>
      </block>
    </view>
  </view>
  <view style="padding-top:10rpx"></view>
  <view>
    <block wx:for="{{articles}}" wx:key='sss'>
      <view class='card' bindtap='articleClick' data-data="{{item}}">
        <view class='article-view'>
          <text class='article-author'>{{item.author}}</text>
          <text class='article-niceDate'>{{item.niceDate}}</text>
        </view>
        <view class='article-title'>{{item.title}}</view>
        <view class='article-view'>
          <text class='article-ChapterName'>{{item.superChapterName}}/{{item.chapterName}}</text>
          <image class='article-collect-img' src="../images/collect_normal.png"></image>
        </view>
      </view>
    </block>
  </view>
</scroll-view>

     上述home.wxml代码中的BannerData 就是home.js中data{}中的BannerData,就是后台返回的数据的list,下面的articles也是一样,使用wx:for来解析list中的数据,代码中item就是list数据中单条的数据。

home.wxss就是home.wxml页面展示的样式 #home.wxss

/* pages/home/home.wxss */

.swiper-container {
  padding: 15rpx;
  position: relative;
}

.swiper-container .swiper {
  height: 400rpx;
}

.swiper-container .swiper .img {
  width: 100%;
  height: 100%;
}

.swiper-container .dots {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 20rpx;
  display: flex;
  justify-content: center;
}

.swiper-container .dots .dot {
  margin: 0 8rpx;
  width: 14rpx;
  height: 14rpx;
  background: #fff;
  border-radius: 8rpx;
  transition: all 0.6s;
}

.swiper-container .dots .dot.active {
  width: 24rpx;
  background: #f80;
}

.card {
  border: 2px solid #fff;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 2px 2px 2px 2px #ccc;
  margin: 8px;
  position: relative;
}

.article-author {
  color: gray;
  font-size: 0.8rem;
  padding-left: 10rpx;
}

.article-title {
  color: black;
  font-size: 0.9rem;
  margin-top: 15rpx;
  margin-left: 5rpx;
}

.article-niceDate {
  color: gray;
  padding-right: 10rpx;
  font-size: 0.8rem;
}

.article-view {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10rpx;
}

.article-ChapterName {
  color: #1296db;
  font-size: 0.8rem;
  margin-top: 30rpx;
  margin-left: 5rpx;
}

.article-collect-img {
  width: 40rpx;
  margin-right: 10rpx;
  margin-top: 30rpx;
  flex: none;
  height: 38rpx;
}

四、点击事件

     这个小程序最终打开基本都是以链接的形式,所以这里使用了web-view,也是测试版才能使用,否则需要注册个体或者公司信息。

     点击事件在home.wxml中声明,在home.js中实现。

举个栗子

<swiper-item data-id="{{item.id}}" data-url="{{item.url}}">
          <image src="{{item.imagePath}}" class="img" bindtap='swipclick' data-data="{{item}}"></image>
        </swiper-item>

     代码中的bindtap就是声明一个点击事件

 //轮播图点击事件
  swipclick: function(e) {
    console.log(e.currentTarget.dataset)
    app.globalData.webUrl = e.currentTarget.dataset.data.url
    // app.globalData.fromWhere='homeBanner'
    wx.navigateTo({
      url: '../web/web'
    });
  },

     在home.js中实现这个点击事件,此处就是携带一个url跳转到web-view的页面来展示。

     这里主要分析了首页的页面实现,其他页面基本思路都是一样。

分析完毕,欢迎指点!!!

小程序二维码.jpg

项目源码

简书地址 www.jianshu.com/p/328a2720e…