WeChat Development Practical Zhihu Daily

零下一度
Release: 2017-05-22 11:26:34
Original
2150 people have browsed it

Preface

After reading so many introductions to mini programs, you must have a certain understanding of mini programs. This article will no longer focus on getting started. Now we will practice it through a Zhihu Daily mini program to deepen our understanding of the WeChat mini program API.

Okay, let’s get started.

The actual battle begins

First of all, let’s take a look at the results of the Zhihu Daily we are going to do today.
As shown below. However, due to space issues, today we will only talk about the completion of the home page, which includes interaction with the backend, page layout, data rendering, event response, etc. It basically covers all development on how to make a single page.

WeChat Development Practical Zhihu Daily

Zhihu Daily Mini Program Home Page

1. Resource Preparation

Zhihu Daily-Simple Version API:

new
s-at.zhihu.com/api/4/news/latest 今日热文
news.at.zhihu.com/api/4/news/
before
/  更多往日热文
Copy after login

The above two addresses are the APIs of the homepage we are going to do today. We will initiate a request request and get back the data for rendering.

2.Homepage JS

We will start writing code below. Please keep the directory structure of the homepage consistent with the picture below.

WeChat Development Practical Zhihu Daily

Three files on the home page

Okay, first let’s write the JS file. The code is as follows, and I have added detailed comments.

// index.js

//index.js
//获取应用实例
var app = getApp()
var utils = require('../../utils/util.js');
//初始化数据
Page({
  data: {
    list: [],
    duration: 2000,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    loading: false,
    plain: false
  },
  //onLoad方法,程序启动自执行,请求知乎日报今日热闻接口
  onLoad: function () {
    var that = this;
    wx.request({
      url: 'http://news-at.zhihu.com/api/4/news/latest',
      headers: { // http头数据
        'Content-Type': 'application/json'
      },
      success: function (res) { //请求成功后的回调
         that.setData({   // 设置返回值
           banner: res.data.top_stories,  //banner图片数据
           list: [{ header: '今日热闻' }].concat(res.data.stories)  //热闻数据list
         })
      }
    })
    this.index = 1;   //方便下拉点击更多时的计数下标,暂可忽略
  },
  //下拉滚动条,点击更多的响应
  loadMore: function (e) {
    if (this.data.list.length === 0) return
    var date = this.getNextDate()
    var that = this
    that.setData({ loading: true });
    wx.request({  // 再次发起请求,请求上一天的热闻
      url: 'http://news.at.zhihu.com/api/4/news/before/' + (Number(utils.formatDate(date)) + 1),  //此此API需要带日期
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {  // 成功回调
         that.setData({
           loading: false,
           list: that.data.list.concat([{ header: utils.formatDate(date, '-') }]).concat(res.data.stories)
         })
      }
    })
  },
  //事件处理函数
  bindViewTap: function(e) {
    wx.navigateTo({
      url: '../detail/detail?id=' + e.target.dataset.id
    })
  },
  //转换时间函数
  getNextDate: function (){
    var now = new Date()
    now.setDate(now.getDate() - this.index++)
    return now
  },

})
Copy after login

Here we briefly talk about a few key points:

2.1 Set data value

Currently the WeChat applet can only support

this.setData({....});
Copy after login

cannot directly specify one Value

this.data.xxxx = '';  //记住,这样是不行的。
Copy after login
2.2 onLoad

This is a method in the pagelife cycle to monitor page loading, which means that every time you enter this page, you must execute it. The method is the same as load in JS.

2.3 Interacting with the server

WeChat applet also uses the request interface to interact with the backend. The specific sample is as follows. I have added comments, so everyone can understand it.

wx.request({
  url: 'test.php', //接口地址
  data: {  // 参数
     x: '' ,
     y: ''
  },
  header: {  // 头信息
      'Content-Type': 'application/json'
  },
  success: function(res) {  // 成功 回调
    console.log(res.data)
  }
})
Copy after login

3. Home page layout index.html

Okay, we have finished writing the js code that interacts with the backend, so we get the data, now we start writing the page layout.

In fact, the WeChat applet also uses a template engine method when rendering pages. And the page value methods are relatively common. It is similar to some other page template engines.

Okay, let's get started. This Page layout is relatively simple.

WeChat Development Practical Zhihu Daily

Layout division

3.1 banner block

First, let’s go find the document, there will be a special banner component,
swiper (click to jump to the document)

We will use this swiper component to write our banner module. There is a note here

swiper Only <swiper-item/> components can be placed in the component, other nodes will be automatically deleted.

// index.html banner模块代码

<swiper indicator-dots="{{indicatorDots}}"
  autoplay="{{autoplay}}" class="banners" interval="{{interval}}" duration="{{duration}}">
    <!-- 循环bannner图片开始-->
    <block wx:for="{{banner}}"> 
      <swiper-item class="banner" >
          <image src="{{item.image}}"  data-id="{{item.id}}" bindtap="bindViewTap" class="banner-image" width="100%" height="100%"/>
          <text class="banner-title">{{item.title}}</text>
      </swiper-item>
    </block>
     <!-- 循环bannner图片结束-->
  </swiper>
Copy after login
3.2 Hot news list module

In fact, the hot news list below is also a list loop. How to make a loop here? We can also query the API documentation to get it.
Use the wx-for attribute, but this is just an attribute. We need to add it to a label to execute it. In order to carry this attribute, the WeChat applet specifically defines a label that has no other function.

Also note that there are many defaults in the WeChat applet:

Use the wx:for control attribute on the component to bind an array, and you can use the data of each item in the array to repeat Render the component. By default, the subscript variable name of the current item in the array defaults to index, and the variable name of the current item in the array defaults to item. If you need to modify it, use wx:for-item to specify the variable name of the current element of the array.

So don’t be surprised by the following item.header, where does the item come from?

The code is as follows:

<view class="news-item-container">
    <block wx:for="{{list}}" wx:for-index="id">
      <text wx:if="{{item.header}}" class="sub-title">{{item.header}}</text>
      <navigator wx:else url="../detail/detail?id={{item.id}}">
        <view class="news-item" >
          <view class="news-item-left">
            <text class="news-item-title">{{item.title}}</text>
          </view>
          <view class="news-item-right">
            <image src="{{item.images[0]}}" class="news-image"/>
          </view>
        </view>
      </navigator>
    </block>
    <button type="primary" class="load-btn" size="mini" loading="{{loading}}" plain="{{plain}}" bindtap="loadMore"> 更多 </button>
  </view>
Copy after login

In addition, there are more click responses here, using the bindtap attribute to specify the response method name.

4. Style sheet index.wxss

I won’t talk about this separately, it is almost the same as the css I usually write. Finally, the source code will be released for everyone to download.

5. Written at the end

This short article just leads you to make a small demo that interacts with the server to deepen your understanding of the ins and outs of the WeChat applet.
The follow-up is in coding....
Stay tuned.

【Related recommendations】

1. WeChat public account platform source code download

2. Little Pigcms (PigCms) micro-e-commerce system operation version (independent micro-store mall + three-level distribution system)

3. WeChat Network King v3. 4.5 Advanced Commercial Version WeChat Rubik’s Cube Source Code

The above is the detailed content of WeChat Development Practical Zhihu Daily. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template