微信小程序开发

2102 查看

微信小程序还在测试阶段,网上有IDE(微信web开发者工具)的破解版,可以在没有AppID情况下进行小程序开发,官方最新版本的IDE(v0.10.101100)也已经支持无AppID配置下开发,相信离正式开放不远了。

项目结构


structure.png


其实小程序的项目结构除了app级文件外并没有太多强制要求,引用时通常文件路径正确即可。

  • app级文件

app.json用来声明程序配置;app.wxss可以定义全局通用样式;app.js定义全局数据、方法以及app生命周期函数等。这些文件的文件名固定,同时必须在项目根目录下,程序编译时直接写死了这些文件的引用路径。其中,app.json文件为必须,否则编译时会直接报错,其他为非必须,但是如果需要,文件路径必须固定。

  • pages文件

通常一个页面对应一个目录,包括.js、.wxml、.wxss、.json文件,文件名称必须与目录名称相同。.wxml文件类似html,声明组件;.wxssw文件类似css文件,声明组件样式,会覆盖app.wxss样式;.json文件为页面配置文件;.js文件定义页面逻辑、数据以及页面(Page)的生命周期等。pages文件必须在app.json中注册后才能使用,注册的第一个page为小程序的首页。

  • 资源文件

包括图片文件等,位置随便放,引用时路径正确即可。

数据绑定与更新

使用双层大括号 {{}} 可以将Page的js文件中声明的data与.wxml组件进行数据绑定,数据更新时,可以使用Page的setData方法更新data,页面会自动更新view。

<scroll-view scroll-y="true" bindscrolltolower="loadMore">  
  <swiper indicator-dots="true" autoplay="true" interval="3000" duration="1000">
    <block wx:for-items="{{imageUrls}}">
      <swiper-item>
        <image src="{{item}}" class="slide-image"/>
      </swiper-item>
    </block>
  </swiper>
</scroll-view>

其中,imageUrls、topics都是Page中声明和初始化的data。另外,WXML提供了wx:for-items方便我们进行列表渲染,另外还有wx:if可以进行条件渲染。

Page( {
  data: {
    pageNum: 0,
    topics: [],
    hidden: false,
    imageUrls: [
'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg', 
'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',      
'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
      ]
  },
  onLoad: function() {
    this.requestTopics(false);
  },
  requestTopics: function (reset) {
    var that = this;
    wx.request( {
      url: 'https://cnodejs.org/api/v1/topics',
      data: {
        page: that.data.pageNum + 1,
        limit: 10,
        mdrender: false
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function(res) {
        that.setTopics(res.data.data, reset);
      }
    });
  },
  loadMore: function (e) {
    this.setData({hidden: false});
    console.log("pageNum=" + this.data.pageNum);
    this.requestTopics(false);
  }
})

这里需要注意的是,setData是Page实例的函数,如果在其他作用域中,例如在网络请求成功的回调中,使用this.setData()是更新不了数据的,因为此处的this取到的并不是Page。因此,通常需要先将Page实例缓存起来再使用。调用其他方法或者data情况类似。

页面模版

公共的、可复用的页面模块我们抽出来作为页面模版(template),更加方便高效。使用<template></template>标签定义一个页面模版,如果在其他页面引用,使用import导入模版即可。

<template name="cnode-topic">
  <navigator url="/pages/topicdetail/topicdetail?topicId={{topic.id}}">
    <view class="topic-item" >
      <view class="topic-title-line">
        <text class="topic-title">{{topic.title}}</text>
        <text class="topic-top" wx:if="{{topic.top}}">置顶</text>
        <text class="topic-good" wx:if="{{topic.good}}">精华</text>                          
      </view>
      <view class="topic-author">
        <image class="author-image" src="{{topic.author.avatar_url}}"></image>
        <text class="small-text author-name">{{topic.author.loginname}}</text>
        <text class="small-text topic-date">{{topic.create_at}}</text>
        <text class="small-text topic-tab">{{topic.tab}}</text>      
      </view>
      <text class="topic-content">{{topic.abstract}}</text>
      <text class="total-button">查看全文</text>
    </view>      
  </navigator>    
</template>

name属性作为template的标识,template有自己的作用域,在引用template时可以传入需要的data。例如:

<import src='topic_item.wxml' />

<view class="topic-list">
    <block wx:for-items="{{topics}}" wx:for-item="topic">
      <template is="cnode-topic" data="{{topic:topic}}" />  
    </block>
</view>

import template的时候,不具有传递性。也就是说假如a.wxml import b.wxml,b.wxml import c.wxml,那么a中是没有引用到c中的template的。

模块化

在JavaScript文件中声明的变量和函数只在该文件中有效,不同的文件中可以声明相同名字的变量和函数,不会互相影响。我们可以将一些公共的代码抽离成为一个单独的js文件,作为一个模块。模块只有通过module.exports才能对外暴露接口。

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 外露接口
module.exports = {
  formatTime: formatTime
}

在需要使用这些模块的文件中,使用require(path)将公共代码引入,即可调用对应的方法。

var util = require( '../../utils/util.js');

Page( {
  setTopics: function(topics, reset) {
    console.log(topics);
    for(var i = 0; i < topics.length; i++) {
      topics[i].abstract = topics[i].content.substring(0, 150);
      topics[i].create_at = util.formatTime(new Date(topics[i].create_at));
    }   
    this.setData({
      topics: reset ? topics : this.data.topics.concat(topics),
      hidden: true,
      pageNum: this.data.pageNum + 1
    });
  }
})

测试截图

使用cnode社区api做的简单的微信小程序:


snapshot.png