WeChat Development Practical Zhihu Daily
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.
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.
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 }, })
Here we briefly talk about a few key points:
2.1 Set data value
Currently the WeChat applet can only support
this.setData({....});
cannot directly specify one Value
this.data.xxxx = ''; //记住,这样是不行的。
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) } })
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.
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>
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
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>
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

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.

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

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.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

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...
