Section 4: Data Extraction of Wechat Widget Program and Application of template

Keywords: REST shell Javascript

In order to optimize demo better, the code is optimized from two parts after referring to the official documents.

Extract the simulated data from page js separately and simulate the returned data more realistically

Create a new folder data in the project, then create a posts-data.js file under the folder, and extract the code of the simulated data from the previous posts.js:

  • posts-data
var local_database = [
    {
        date: "Sep 18 2016",
        title: "It's when shrimps and crabs grow strong",
        img: {
          imgSrc: "/images/post/crab.png",
          avatar: "/images/avatar/1.png",
          headImgSrc: "/images/post/crab.png"
        },
        img_condition:true,
        content: "Chrysanthemum yellow crab is full of fat and tastes autumn. Xu Zhimo takes,"Look at the Flowers of Silver Reed and "Eat Crabs Outside the Building",It's also an elegant thing that we can't miss when we come to Hangzhou in autumn.",
        reading: "112",
        collection: "96",
        author: "Lin Bai Yi",
        dateTime: "24 Hours ago",
        detail: "Chrysanthemum yellow crab is full of fat and tastes autumn. Xu Zhimo classified "seeing the first flowering silvergrass" and "eating crabs outside the building" as the elegant things that we can't miss when we come to Hangzhou in autumn; in Sister Lin's words, "chewing and sealing the tender jade are both full and the shell is convex and fragrant with red grease lumps"; in Shishuo Xinyu, Jin Bizhuo sighed "holding the wine cup on the right hand, crab cheek on the left, patting the floating wine boat, which is enough for a lifetime." The long road of life, food and love can not be disappointed? So as a food, I suddenly want to recall my taste bud memory. The autumn crab in memory is the flavor of the family, full of strong family affection.\n\n Who comes from mountains, lakes and seas, but is confined to day and night, kitchen and love? Mother, thoughtful, intelligent and patient. Before eating crabs, they always take out a few tools and enjoy it. Tell US crabs to the cold, need to be accompanied by ginger tea to dispel cold, in the equipped rice vinegar dish, also add ginger silk and perilla, the former drive cold, the latter increase aroma. Make chrysanthemum tea, time is quiet, we wait.",
        postId: 0,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100003507bR0gDKBm.m4a?fromtag=38",
            title: "Endless Night-Chyi Chin",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000001TEc6V0kjpVC.jpg?max_age=2592000"
        }
    },
    {
        title: "Billy·Lynn's Midfield Story",
        img: {
          imgSrc: "/images/post/bl.png",
          avatar: "/images/avatar/1.png",
          headImgSrc: "/images/post/bl.png"
        },
        img_condition: true,
        content: ""Ang Lee is a director who will never repeat himself. This film will be highly original Ang Lee's new film,"Billy Lynn's Long Half-time Rest,"formally renamed"Half-court No War".",
        reading: 62,
        detail: ""Ang Lee is a director who will never repeat himself. This film will be very original." Ang Lee's new film, "Billy Lynn's Long Half-time Rest", formally renamed "No War in Half-court". After the trailer's first exposure, it was regarded as next year's Oscar seed player. The film was adapted from a bestseller of the same name. The original novel won the National Book Award. Also be BBC It is one of the 12 greatest English novels in the 21st century. Billy, a 19-year-old Texas boy·Lynn joined the army to participate in the Iraq War. He survived a firefight. Accidents and comrades became the focus of public attention and were portrayed as heroes. They then returned home to receive medals at half-time in football. This war hero is facing unprecedented spiritual suffering... Why did Ang Lee choose this movie to shoot? Because Ang Lee wants to challenge unprecedented technical challenges: at 120 frames per second, 4 K,3D All-round combination of technology has set off a film visual revolution. What do you mean? The so-called "movie is a 24-frame-per-second lie", of which 24 is the number of frames.",
        collection: 92,
        dateTime: "24 Hours ago",
        author: "Lost City",
        date: "Nov 20 2016",
        postId: 1,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100003GdCmG4NkEOR.m4a?fromtag=38",
            title: "Be possessed-Jonathan Lee",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000002xOmp62kqSic.jpg?max_age=2592000"
        }
    },
    {
        //Press alt + shift + F to format code styles
        title: "When we talk about economics, what are we talking about??",
        img: {
          imgSrc: "/images/post/sls.jpg",
          avatar: "/images/avatar/3.png",
          headImgSrc: "/images/post/sls.jpg"
        },
        img_condition: true,
        content: "Introductory When I communicate with students after class, and when I know how to read about the topic of "economy", I often encounter such situations:...",
        detail: "1 Introduction\n\n When I communicate with students after class, and when I read the topic about "economy" in my mind, I often encounter the situation that some people apply the knowledge of "economic theory" to explain the economic events in reality, and find that many things do not make sense, or find that the theory tells us that "it is contrary to reality". Some students often tell me: What's the use of economics? To illustrate this, I often explain it in two ways. I try to explain what economics is and where its boundaries lie from the perspective of solving problems that I am good at and the methods they can understand.\r\n\n2 "Sketch "and" oil portrait "We can use sketch or oil portrait to draw portraits of people. Oil portraits can preserve the details and characteristics of the characters to the greatest extent, while simple sketches ignore many details. Although sketches neglect many details of the characters, we can still easily identify who the characters are. Why? Because this method retains the most prominent characteristics of the characters, we can ignore the secondary characteristics and make the judgement of the characters.\n\n2.1 "For the vast majority of non-economics majors (with a master's degree or above in economics), the economics people come into contact with is primary microeconomics. The so-called primary microeconomics is a kind of sketch of economic problems. For example, the one-way demand function widely used in primary microeconomics textbooks: y=bx+a,The only variable in demand is the price of the product. But intuitively, we can conclude that price is not the only factor affecting demand in reality, so we can think that this model is distorted in describing economic problems. However, this distortion is necessary and meaningful. Its significance lies in that it helps to reveal the impact of price on demand, not in denying other factors affecting demand.——",
        reading: 62,
        collection: 92,
        author: "Know about",
        date: "Nov 12 2016",
        dateTime: "Three days ago",
        postId: 2,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100004HLusI2lLjZy.m4a?fromtag=38",
            title: "Daughter love-Wan Xiaoli",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000004Wv5BO30pPc0.jpg?max_age=2592000"
        }
    },
    {
        title: "WeChat·Installation Guide for Small Program Development Tools",
        img: {
          imgSrc: "/images/post/xiaolong.jpg",
          avatar: "/images/avatar/5.png",
          headImgSrc: "/images/post/xiaolong.jpg"
        },
        img_condition: true,
        content: "In these two days, I have nothing to do, and I have installed the development tool of "Wechat Folding" to play. Following are some tips and usage experiences. In two days I will write an article to evaluate the Wechat applet in detail from the developer's point of view.",
        reading: 102,
        detail: "In these two days, I have nothing to do, and I have installed the development tool of "Wechat Folding" to play. Following are some tips and usage experiences. In two days I will write an article to evaluate the Wechat applet in detail from the developer's point of view.:Wechat applet can't develop game and live broadcasting functions. The upper limit of everyone's attention is 20 (I'm not sure, but I believe it's true, this time it's announced). API There are no video components. Wechat is too big, Apple should have some scruples, but Wechat should make corresponding concessions.)Whether Wechat has a good discussion with Apple is still unknown. After all, it will. AppStore There is a certain impact. Abandoned a large number of javascript After the components, the ecosystem became quite closed, and Wechat's explanation must be: for better performance. So let's wait and see. The entry to the widget is the three-level menu in Wechat, which is“ Tab Add a "small program" under the game found in the column. Anyway, I've never ordered any shopping or games in this column. With Tencent's urinary nature, small programs, like service numbers, have different openness in their relationship chains and important functions. Yes, the high quality interface will only be open to Tencent's sons.",
        collection: 92,
        dateTime: "24 Hours ago",
        author: "A cat is a cat.",
        date: "Nov 20 2016",
        postId: 3,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100002mWVx72p8Ugp.m4a?fromtag=38",
            title: "Dust in The Wind-Wolf",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000001VaXQX1Z1Imq.jpg?max_age=2592000",
        }
    },
    {
        title: "From visual to tactile VR Gloves give you real touch",
        img: {
          imgSrc: "/images/post/vr.png",
          avatar: "/images/avatar/3.png",
          headImgSrc: "/images/post/vr.png"
        },
        img_condition: true,
        content: "8 Jan. 29, according to foreign media VentureBeat Reported, a family named Dexta Robotics The company recently released a new product that promises to change the way virtual reality hands track and interact.",
        reading: 102,
        detail: "News, according to foreign media VentureBeat Reported, a family named Dexta Robotics The company recently released a new product that promises to change the way virtual reality hands track and interact. The product is named“ Dexmo",It is a futuristic exoskeleton worn like a glove on the hand. It has a large number of built-in components that can work with VR Experience interacts to help you feel virtual objects in your hands. Dexmo according to Dexta " Dexmo It's a mechanical exoskeleton for your hands. It captures the movement of your hand and provides instant force feedback. become pregnant Dexmo,You can feel the size, shape and hardness of virtual objects. You can touch the digital world. There are several products on the market to deal with hand interaction in virtual reality, and related products are about to enter the market. For example, popular HTC Vive The helmet is equipped with a controller that allows the tracking system to see your hands so that you can interact with objects in a particular experience. Later this year, Oculus Similar hand control products will be shipped Oculus Touch. 10 In January, Sony will also start shipping two PlayStation Move Hand Controller PS VR. Leap Motion Even further: sensors are used to track finger and hand movements.",
        collection: 26,
        dateTime: "24 Hours ago",
        author: "Deep white",
        date: "Nov 20 2016",
        postId: 4,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100000Zn0vS4fKKo8.m4a?fromtag=38",
            title: "Silence is gold-Leslie Cheung",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000003at0mJ2YrR2H.jpg?max_age=2592000"
        }
    },
    {
        title: "Aiqi Yichuangwei Develops Strategic Cooperation and Jointly Layouts Open Entertainment Ecology",
        img: {
          imgSrc: "/images/post/xiaolong.jpg",
          avatar: "/images/avatar/5.png",
          headImgSrc: "/images/post/xiaolong.jpg"
        },
        img_condition: true,
        content: "Akieyi and Skyworth are the leading online video brands in China.",
        reading: 96,
        detail: "IQI and Skyworth are the leading online video brands and household appliances brands in China. Both sides have been committed to innovation, providing users with quality service experience and product experience. It is learnt that Aiqi Art and Skyworth will expand from capital to VIP In-depth cooperation in all aspects of membership services. With this cooperation, IQYI will invest strategically in the Cool Start Company of Skyworth, which owns a high-end Internet TV brand. Starting from the next fiscal year, Skyworth's Internet TV will be preset through the Galaxy Internet TV Integrated Broadcasting and Control Platform. VIP Membership services and related content. This bundling terminal and VIP The new sales mode of content will greatly enhance the experience of Internet TV terminal users and give users more choice of high quality content.",
        collection: 26,
        dateTime: "21 Hours ago",
        author: "Deep white",
        date: "Nov 20 2016",
        postId: 5,
        music: {
            url: "http://ws.stream.qqmusic.qq.com/C100002I8eGJ28BI17.m4a?fromtag=38",
            title: "Friend-Alan Tam",
            coverImg: "http://y.gtimg.cn/music/photo_new/T002R150x150M000004eGsCN3SUheO.jpg?max_age=2592000"
        }
    },
]

module.exports = {
    postList: local_database
}

In this way, you just need to introduce the following code into the previous posts.js page.

var postsData = require('../../data/posts-data.js');

At this point, the posts.js file becomes like this:

  • posts.js
var postsData = require('../../data/posts-data.js');

Page({
  /**
   * Initial data of pages
   */
  data: {

  },

  /**
   * Life Cycle Function -- Listening for Page Loading
   */
  onLoad: function (options) {
    //Equivalent to setting values in page initialization data
    this.setData({
      posts_key: postsData.postList
      });
  }
})
Template template is a code reuse solution provided by wechat widget, which can extract wxml and wxss code to achieve the purpose of code reuse.

Now, extract the news list code from the previous posts.wxml code and place it in posts-item-template.wxml under a new folder posts-item, which needs to be wrapped with a temolate tag.

  • posts-item-template.wxml
<template name='postItem'>
  <view class='posts-container'>
      <view class='posts-author-date'>
        <image wx:if='{{item.img_condition}}' src='{{item.img.imgSrc}}'></image>
        <text>{{item.date}}</text>
      </view>
      <text class='posts-title'>{{item.title}}</text>
      <image class='posts-image' src='{{item.img.imgSrc}}'></image>
      <text class='posts-content'>{{item.content}}</text>
      <view class='posts-like'>
        <image src='/images/icon/chat.png'></image>
        <text>{{item.reading}}</text>
        <image src='/images/icon/view.png'></image>
        <text>{{item.collection}}</text>
      </view>
  </view>
</template>

This file needs to be introduced in front of the previous posts. wxml code:

<import src='/pages/posts/posts-item/posts-item-template.wxml'/>

Write in the original position of the extracted code:

<template is='postItem' data='{{item}}' />

Among them, is='postItem'is the name of the template tag in posts-item-template.wxml, and then the posts.wxml code becomes like this:

  • posts.wxml
<import src='/pages/posts/posts-item/posts-item-template.wxml'/>

<view>
  <swiper indicator-dots='true' autoplay='true'>
    <swiper-item>
      <image src='/images/xiaolong.jpg'></image>
    </swiper-item>
    <swiper-item>
      <image src='/images/vr.png'></image>
    </swiper-item>
    <swiper-item>
      <image src='/images/bl.png'></image>
    </swiper-item>
  </swiper>
  <block wx:for='{{posts_key}}' wx:for-item='item' wx:for-index='index'>
    <template is='postItem' data='{{item}}' />
  </block>
</view>

After completing the extraction of wxml, we continue to extract the wxss code. Similarly, create a new posts-item-template.wxss in the posts-item directory, and write in the previous posts.wxss style about the news list section.

  • posts-item-template.wxss
.posts-container{
  display: flex;
  flex-direction: column;
  margin-top: 20rpx;
  margin-bottom: 40rpx;
  background-color: #fff;
  border-bottom: 1px solid #ededed;
  border-top: 1px solid #ededed;
  padding-bottom: 5px;
}

.posts-author-date{
  margin: 10rpx 0 20rpx 10rpx;
}

.posts-author-date image{
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  vertical-align: middle;
}

.posts-author-date text{
  margin-left: 20rpx;
  vertical-align: middle;
  margin-bottom: 5px;
  font-size: 26rpx;
}

.posts-title{
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  margin-left: 10px;
}

.posts-image{
  width: 100%;
  height: 340rpx;
  margin: auto 0;
}

.posts-content{
  color: #666666;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  margin-left: 20rpx;
  letter-spacing: 2rpx;
  line-height: 40rpx;
}

.posts-like{
  font-size: 13px;
  flex-direction: row;
  line-height: 16px;
  margin-left: 10px;
}

.posts-like image{
  height: 16px;
  width: 16px;
  margin-right: 8px;
  vertical-align: middle;
}

.posts-like text{
  vertical-align: middle;
  margin-right: 20px;
}

In front of the posts.wxss code, you need to introduce the above file:

@import '/pages/posts/posts-item/posts-item-template.wxss';

At this point, the posts.wxss code becomes the following:

  • posts.wxss
@import '/pages/posts/posts-item/posts-item-template.wxss';

swiper{
  width: 100%;
  height: 500rpx;
}

image{
  width: 100%;
  height: 500rpx;
}

Above is the use of js analog data extraction and a simple attempt to template template template application, the current wechat widget template, does not support the reuse of js files, it has to be said that it is a pity, hope that the future version can support.

Posted by mike760534211 on Fri, 17 May 2019 01:05:11 -0700