Table of Contents
Preface
The actual battle begins
1. Resource Preparation
2.Homepage JS
2.1 Set data value
2.2 onLoad
2.3 Interacting with the server
3. Home page layout index.html
3.1 banner block
3.2 Hot news list module
5. Written at the end
Home WeChat Applet WeChat Development WeChat Development Practical Zhihu Daily

WeChat Development Practical Zhihu Daily

May 22, 2017 am 11:26 AM

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

What are the development tools for H5 and mini program? What are the development tools for H5 and mini program? Apr 06, 2025 am 09:54 AM

H5 development tools recommendations: VSCode, WebStorm, Atom, Brackets, Sublime Text; Mini Program Development Tools: WeChat Developer Tools, Alipay Mini Program Developer Tools, Baidu Smart Mini Program IDE, Toutiao Mini Program Developer Tools, Taro.

Detailed tutorial on how to buy and sell Binance virtual currency Detailed tutorial on how to buy and sell Binance virtual currency Mar 18, 2025 pm 01:36 PM

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.

See all articles