“If you hand it over to the book, the wisdom will be passed on. This article will take you to use cloud development to quickly develop a complete campus second-hand book mall.

Introduction:

There is a common phenomenon, many university graduates or move campus, piles and piles of books have been disposed casually, as a n experienced person, every time I think of is very sad, alas, and the cause of this happening, I think mostly boils down to the school, on the one hand does not provide convenient on the platform, on the other hand, the propaganda does not reach the designated position, based on the development of the small procedures. Here are some typical examples encountered in the development process to explain the implementation process, you can take a look at……

A: Login registration page

At present, the small program has a detailed login specification, referring to the official example, the login entrance of this program has done the following processing:

  1. In the part that needs to involve user information, enter with Modal prompt, such as: tourists release, purchase, etc
  2. Personal center, not logged in default display “click login” button

Ok, let’s take a look at the login page:

  • Obtaining mobile phone number (relevant code) :
<button class="phone" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">
                  <block wx:if="{{phone==''}}">Please click to obtain your mobile phone number</block>
                  <block wx:if="{{phone! = = '}}"> {{phone}}</block>
                  <image wx:if="{{phone==''}}" class="right" src="/images/right.png" />
</button>
Copy the code
 // Get the user's mobile phone number
      getPhoneNumber: function(e) {
            let that = this;
            // Determine whether the user is authorized to confirm
            if(! e.detail.errMsg || e.detail.errMsg ! ="getPhoneNumber:ok") {
                  wx.showToast({
                        title: 'Failed to obtain mobile phone number'.icon: 'none'
                  })
                  return;
            }
            wx.showLoading({
                  title: 'Get phone number in... ',
            })
            wx.login({
                  success(re) {
                        wx.cloud.callFunction({
                              name: 'regist'.// Corresponds to the cloud function name
                              data: {
                                    $url: "phone".// Cloud routing parameters
                                    encryptedData: e.detail.encryptedData,
                                    iv: e.detail.iv,
                                    code: re.code
                              },
                              success: res= > {
                                    wx.hideLoading();
                                    // Set the mobile phone number
                                    that.setData({
                                          phone: res.result.data.phoneNumber
                                    })
                              },
                        })
                  },
            })
      },
Copy the code
  1. Only the front-end core code is shown here. Obtaining the mobile phone number involves the decryption process, which needs to be implemented with the cloud function. For details, please refer to the complete Demo registration page code
  2. Currently, the interface is for non-individual developers and has completed the opening of certified applets (excluding overseas entities).
  • Check of common contact methods:
if(! (/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(email))) {
                  wx.showToast({
                        title: 'Please enter your usual email address'.icon: 'none'
                  });
                  return false;
            }
Copy the code

Similarly related regulars:

/ / cell phone number/ ^ [1] [3.4.5.6.7.8.9] [09 -] {9} $// / QQ number
/^\s*[. 09 -] {5.11}\s*$/
/ / WeChat ID
/^[a-zA-Z]([-_a-zA-Z09 -] {5.19}) + $/Copy the code

Currently commonly used mobile phone number, it seems that the difference between 10 and 12 fields did not.

Two: release information page

  • Step bar implementation

There are a few small things to note about the release page:

  1. The step bar at the top is constantly changing with the operation flow.
  2. When the steps change, there is a landscape switch animation
  3. Price Settings, using stepper

These points are mentioned above because they all come from the same source — the Vant component

A tutorial on how to use this component can be found on the corresponding website

youzan.github.io/vant-weapp/

Using components is much more efficient, avoids rework, and can refer to the writing of some components. There is still a lot to learn.

  • Textarea little attention

If the following tabbar is written by the user instead of using the native tabbar, there will be a penetration problem, as shown in the following figure:

My common solution is to dynamically change the focus state of the Textarea. When the area is clicked, the focus is set to display the real Textarea. When the area is out of focus, the textarea is displayed as view layer, and the code is as follows:


<view class="beibox">
      <view wx:if="{{! focus}}" bindtap="focus" >{{beizhu? Beizhu :' Please enter information '}}</view>
      <textarea wx:if="{{focus}}" focus="{{focus}}" bindblur="loose" bindinput="beiInput" value="{{beizhu}}"></textarea>
</view>
Copy the code
      data: {
            beizhu:' '.focus: false // Default is not focus
      }
    // Click focus to show textarea hidden view
      focus() {
            let that = this;
            that.setData({
                  focus: true})},// Lose focus and hide textarea to display view
      loose() {
            let that = this;
            that.setData({
                  focus: false})},Copy the code

Three: the home page

The left picture above is the initial style of the home page after entering, the right picture is the dynamic page after sliding, about the style layout of the page, using Flex can be easily done, we focus on the following point:

  • Monitor screen scrolling to achieve dynamic response

In the second example above, as the page slides down, the category bar rises to the top and a back to the top button appears below. This works:

Monitor the screen slide height and render the element when it is greater than a certain value we set

Here we need to use one of the page’s event handlers: onPageScroll

// Monitor screen scrolling
      onPageScroll: function(e) {
            this.setData({
                  scrollTop: (e.scrolltop) * (wx.getSystemInfoSync().pixelRatio)})},Copy the code
  1. The function retrieves how far the page has been scrolled vertically (in px), but we use RPX to calculate the page layout, so we then multiply the device pixel ratio to get the corresponding RPX value
  2. Wx: If or Hidden is used to control display and hidden in the view view layer. The difference lies in that: Wx: If is destroyed every time it is hidden, while hidden is just not displayed, but it is still rendered to the page. The specific use effect can be viewed at the view debugging effect.

Here is a complete example of returning to the top

<view class="totop" bindtap="gotop" hidden="{{ scrollTop<500 }}">
       <image  lazy-load src="/images/top.png" />
</view>
Copy the code
      data: {
            scrollTop: 0 // The initial roll height is 0
      },
        // Monitor screen scrolling
      onPageScroll: function(e) {
          this.setData({
              scrollTop: parseInt((e.scrollTop) * wx.getSystemInfoSync().pixelRatio)
          })
      },
      // Return to the top
      gotop() {
            wx.pageScrollTo({
                  scrollTop: 0})},Copy the code

Four: Details page

  1. Small program layout as long as you master a Flex, basically enough, so here but more style issues, when the time comes if you have questions can view the full demo, there are annotations.

  2. Because of the limitation of objects and functions of this small program, there is less shopping cart function compared with the complete mall. Payment and purchase are completed in the detail page of goods. There are two points involved here, one is to place an order to buy, and the other is to notify after purchase.

  • Pay and withdraw cash in small program

Not only the payment, but also the withdrawal, this program has the help of the module tenpay, detailed introduction:

www.npmjs.com/package/ten…

For example use in the small program, refer to the previous community previously published article:

10 lines of code for small program payment function! 丨 of actual combat

Of course, the previous article is to teach you how to realize the payment, and the withdrawal process is the same, first go to tenpay merchant payment to balance instructions, and then take a look at the relevant code of this program, read it for sure to understand.

  • Send a notification
  1. This program is divided into two types of notification: SMS notification, email notification
  2. Usage scenario: After placing an order, the user notifies the seller by SMS + email. After placing an order, the user notifies the seller by email when the order status changes.

Say a little digression: small program has a built-in template notification, in the user active trigger after 7 days can push template information, before writing this program carefully considered, finally abandoned, after all seven days, not every book is so popular.

Email only needs to have an account, SMS notification is to cost, of course, the effect is better than email, configuration, the difficulty are the same, we take SMS as an example:

  1. First go to Tencent cloud application SMS API:

cloud.tencent.com/product/sms

Set SMS signatures and templates as prompted.

  1. Configuring cloud Functions

Create a new SMS cloud function with the following code:

    const cloud = require('wx-server-sdk')
    const QcloudSms = require("qcloudsms_js")
    const envid = 'zf-shcud'; // Cloud development environment ID
    const appid = 140000001 // Replace it with the cloud SMS AppID and AppKey you applied for
    const appkey = "abcdefghijkl123445"
    const templateId = 1234 // Replace it with the ID of the template you applied for
    const smsSign = "Tencent Cloud" // Replace it with the signature you requested
    cloud.init({
      env: envid,
    })
    // Cloud function entry function
    exports.main = async (event, context) => new Promise((resolve, reject) = > {    
      /* Single SMS example is a complete example, more functions please directly replace the following code */
      var qcloudsms = QcloudSms(appid, appkey);
      var ssender = qcloudsms.SmsSingleSender();
      var params = ["Test content"];
      // Get the mobile phone number that sent the SMS
      var mobile = event.mobile
      // Get the phone number country/area code
      var nationcode = event.nationcode
      ssender.sendWithParam(nationcode, mobile, templateId, params, smsSign, ""."", (err, res, resData) => {
          /* Set up the request callback processing, this is just a demonstration, you need to customize the corresponding processing logic */
          if (err) {
            console.log("err: ", err);
            reject({ err })
          } else {
            resolve({ res: res.req, resData })
          }
        }
      );
    })
Copy the code

Cloud.init ({env: envid}); cloud.init({env: envid});

5. Launch page design

The start page is also a highlight of this program, the first entry is a beautiful picture gives a person a sense of physical and mental pleasure, we will talk about this in detail how to do:

What elements?

  1. Full screen background
  2. Countdown jump

Before I say this, please note that the entire page is full screen, so here we need to configure the page parameters:

Configure this in.json on this page:

{
  "navigationStyle":"custom"
}
Copy the code

That’s full screen, so let’s style the page:

<view class="contain">
     <view class="go">
             <button  bindtap="go">Skip the {{count}} s</button> 
     </view>
     <image class="bg" src="{{bgurl}}"></image>
</view>
Copy the code
.contain {
      width: 100%;
      height: 100%;
      position: relative;
}
.bg {
      position: absolute;
      left: 0rpx;
      top: 0rpx;
      width: 100%;
      height: 100%;
      z-index: -1;
}
.go {
      position: absolute;
      right: 30rpx;
      top: 150rpx;  
      z-index: 9;
}
.go button {
      font-size: 28rpx;
      letter-spacing: 4rpx;
      border-radius: 30rpx;
      color: # 000;
      background: rgba(255.255.255.0.781);
       display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      width: 160rpx;
      height: 60rpx;
}

Copy the code

Styles are done quickly, so let’s talk about the JS part.

  • Countdown function:
countDown: function() {
            let that = this;
            let total = 3;// Count down to 3 seconds
            this.interval = setInterval(function() {
                  total > 0 && (total--, that.setData({
                        count: total
                  })), 0 === total && (that.setData({
                        count: total
                  }), wx.switchTab({
                        url: "/pages/index/index"
                  }), clearInterval(that.interval));
            }, 1e3);
      },
Copy the code
  • background
  1. There are two ways to implement this: the first is a local path, and the second is a reference to a remote address (which can be dynamically changed through the interface)

  2. The first benefit is directly using local image, loading speed, the second can change at any time start the figure, two ways are tried, finally I recommend using the first way, using local image, if using a remote address, enter hang there will be a short time, for the first time experience is bad, of course, you can also try to put the picture compressed further compression, There is no slow loading, but resolution is an issue, so how to use it depends on the product.

conclusion

On paper will sleep shallow, never know the matter want to practice, the above summary is to develop this program, I think of the typical problems in practice there will be more interesting question, “baidu” oriented programming is one aspect, but I’m more advice “for the official document”, many problems actually official document has very detailed instructions and code samples, If you’re struggling to read the documentation, I suggest you sit back and familiarize yourself with HTML, CSS, and javascript, and then you’ll look back and say, “Oh, there you go.”


If you want to know more about the cloud development of CloudBase related technical stories/technical combat experience, please scan the code to follow [Tencent cloud development] public account ~

About Cloud Development

CloudBase is a product solution of cloud integration. It adopts serverless architecture, eliminates operation and maintenance transactions such as environment construction, supports one cloud and multiple terminals, and helps to quickly build small programs, Web applications and mobile applications.

  • Technical documentation: www.cloudbase.net/
  • Wechat search: Tencent Cloud Development, get the latest progress of the project