preface

Tanabata has just passed, presumably you for the beloved taπŸ’• spent a lot of money on things. Recently, I was studying wechat small program development during the summer vacation. I developed a fake APP wechat small program with two like-minded partners. This article will share with you some JS logic and page design, as well as some experience encountered bugs. Hope to be able to help some small program beginners.

Project development preparation

  • Wechat developer tools
  • VScode
  • Fiddler 4 (a great little program for drawing pictures)
  • Get micro channel small program
  • Wechat applets development document
  • Have a good vant component library

Project objectives

  • The whole project is a full stack project based on small program cloud development, using cloud database for data operation. Youjun 😘 is responsible for the purchase page, product details page, search page, brand classification page, if you want to know more, you can click the portal. I was mainly responsible for the login function and “my” page writing and the implementation of the purchase function.

Functional presentation and code analysis


Login feature implementation and page style

The page display


Structure of the code

<view class="login__hd">
  <view class="login-1-1">
    <view bindtap="return">
      <image src="https://cdn.poizon.com/node-common/YmFja0AzeDE1OTM3NTU3NDQ4NDk=.png" class="login-1-1-left"></image>
    </view>
    <view class="login-1-1-auto"></view>
    <view bindtap="more">
      <image src="https://cdn.poizon.com/node-common/aG9tZUAzeDE1OTM3NTU3MDU5MjM=.png" class="login-1-1-right"></image>
    </view>
  </view>
  <view class="login__hd_title">
    <h1>The login</h1>
  </view>
</view>
<view class="login__bd">
  <view class="login__bd_pic">
    <image class="image-1"></image>
    <image class="image-2"></image>
  </view>
  <view class="login__bd_main">
    <button class="user-btn1 " openType="getUserInfo"  bindgetuserinfo="getUserInfo" >WeChat login</button>
    <button  class="user-btn3 {{isAgreed? 'active1': ''}}" bindtap='showtips' >WeChat login</button>
    <button class="user-btn2">Mobile number login/registration</button>
  </view>
  <view class="login__bd_info">
    <view class="check_btn {{activeIndex == 1? 'active2': ''}}" bindtap="agree"></view>
    <view class="check_txt">
      <h1>Read and agree<h2 bindtap="show_detail">User agreement, Privacy Policy, buyer's notice</h2>
      </h1>
    </view>
  </view>
</view>
Copy the code

When we do not check the user protocol, we cannot log in wechat, so I use two buttons with the same style here, one of which is bound to a new class name {{isAgreed? ‘active1’: ‘}} and the same principle is bound to {{activeIndex == 1? ‘Active2 ‘: ‘}} on the checkbox label. The following JS logic can be used to authorize login after checking the protocol

JS logic code

Page({
  data: {
    activeIndex: 0.isLogged: false.isAgreed: false
  },
  showtips() {
    if (!this.data.isAgreed) {
      wx.showToast({
        title: 'Please check the protocol first'.icon: 'none'})}},agree() {
    if (this.data.activeIndex == 0) {
      this.setData({
        activeIndex: 1.isAgreed: true})}else {
      this.setData({
        activeIndex: 0.isAgreed: false})}console.log(this.data.isAgreed);
  },
  getUserInfo(e) {
    // console.log(e);
    // console.log(this.data.isAgreed);
    if (e.detail.userInfo == null) {
      wx.switchTab({
        url: '.. /login/login'})},else {
      this.setData({
        isLogged: true
      })
      console.log(this.data.isLogged);
      if (this.data.isLogged) {
        wx.switchTab({
          url: '.. /buy_page/page/buy/buy'}}}}),show_detail() {
    wx.navigateTo({
      url: '.. /login_detail/login_detail',})}})Copy the code

Payment page Style

The page display


Structure show

<van-cell title="Consignee: Liu Xiaotong" icon="location-o" value="187 * * * * 1206" size="large" label=Beijing Bytedance Technology Co., LTD. is-link />

<van-card price="{{goods.price}}" desc="L number x1" title="{{goods.title}}" thumb="{{goods.pic}}" />
<van-cell-group>
  <van-cell title=Sf Express value="RMB 18" />
  <van-cell value-class="cell2" title="Coupon" value="- $15" border="{{ false }}" is-link />
</van-cell-group>
<view class="check_txt">
  <h1>1. If the seller fails to deliver the goods within 36 hours and the transaction is closed and the platform does not match new orders for you, you will receive 28.00 Yuan in cash and 170 yuan in total in full discount coupons as compensation.</h1>
  <h1>2. Each commodity traded is identified by the platform for the real object. In view of the volatility of commodity price and the fact that there is only one item for each style and size for sale, refund of price difference is not supported.</h1>
  <h1>3, enterprise merchant ID:B21031855774654, because the goods unsealed identification, does not support seven days without reason to return.</h1>
  <h1>By submitting an order, you agree to the buyer's instructions<h2 bindtap="show_detail">Buyers requirements</h2>
  </h1>
</view>
<view class="pay_foot">
  <view class="payMoney">
    <h1>Actual payment: οΏ₯<h2>{{newPrice}}</h2></h1>
    <! - save ID -- -- >
    <van-button bind:click="pay" data-id="{{goods.id}}" data-title="{{goods.title}}"data-price="{{goods.price}}"data-pic="{{goods.pic}}" class="b1" type="primary" size="small" color="#01B8B9" square="true" custom-style="width: 200rpx">Submit orders</van-button>
  </view>
</view>
Copy the code

The address on the payment page is van-cell. Properties you can set information such as title, icon, and Lable

The product information is data-bound, and the product ID will be passed when the last page is clicked

JS logic code

  gotoPay(e) {
    wx.navigateTo({
      url: '/pages/buy_page/page/pay/pay? id='+this.data.id,
    })
  }
Copy the code

Then the payment interface connects to the cloud database, queries the information of the product through the id transmitted and setData

  const db = wx.cloud.database()
  const dewuCollection = db.collection('dewu')
  
  data: {
    goods: [].newPrice: 0.id: ' '
  },
  
  async onLoad(e) {
    console.log(e);
    let id = e.id;
    console.log(id);
    await dewuCollection
      .doc(id)
      .get()
      .then(res= > {
        // console.log(res.data);
        let Homedata = res.data
        this.setData({
          goods: Homedata,
          id: id
        })
      })
  },
})
Copy the code

The cloud database file can be written in CSV or JSON format and imported. The cloud database format can be obtained here

My page style

The page display

Structure of the code

 <view class="weui-cells weui-cells_after-title my_tools"> <! -- Purchase bar --><block wx:for="{{buy}}" wx:key="index">
        <navigator style="border-bottom: none" url="{{item.url}}">
            <view class="weui-cell weui-cell_access weui-cell_example ">
                <view class="weui-cell__hd">
                    <image class="icon-img" src="{{item.icon}}"></image>
                </view>
                <view class="weui-cell__bd">{{item.title}}<p>All Orders 2</p>
                </view>
                <view class="weui-cell__ft"></view>
            </view>
        </navigator>
    </block><! -- Other columns --><block wx:for="{{collect}}" wx:key="index">
        <navigator url="{{item.url}}">
            <view class="weui-cell weui-cell_access weui-cell_example ">
                <view class="weui-cell__hd">
                    <image class="icon-img" src="{{item.icon}}"></image>
                </view>
                <view class="weui-cell__bd">{{item.title}}</view>
                <view class="weui-cell__ft"></view>
            </view>
        </navigator>
    </block>
</view>
Copy the code

Purchase functionality implementation (key)

The page display


The design of the page is relatively simple, which can be realized with vant components. The van-tab in the head is sticky on the top, and the settlement column at the bottom is retained with position:fixed at the bottom

Structure of the code

<van-tabs color='black' sticky active="a">
  <van-tab title="To be paid" name="a">
    <view class="buy__info page1">
      <view class="buy__info_goods" wx:for="{{goods}}" wx:key="index">
        <! - select - >
        <view class='icon'>
          <icon wx:if="{{item.selected}}" type="success" color="#00BABA" size="20" bindtap="selectedCart"
            data-index="{{index}}" />
          <icon wx:else type="circle" bindtap="selectedCart" size="20" data-index="{{index}}" />
        </view>
        <! - goods -- -- >
        <van-card price="{{item.price}}" desc="X {{item.value}}" title="{{item.title}}" thumb="{{item.pic}}" />
        <! - delete - >
        <view class='right'>
          <image
            src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic175.nipic.com%2Ffile%2F20180804%2F24144945_114304501035_2.jpg& Refer=http%3A%2F%2Fpic175.nipic.com & app = 2002 & size = f9999, 10000 & q = a80 & n = 0 & g = 0 n & FMT = jpeg? = 1631876010 & t = e1da2162c6dc0c2bd the SEC 878cad1a269e24d'
            bindtap='delete' data-index="{{index}}"></image>
        </view>
        <! Settlement -- -- - >
        <view class="cart-bottom">
          <icon wx:if="{{CheckAll}}" class="cart-icon" type="success" color="#00BABA" size="20" bindtap="select"
            data-index="{{index}}" />
          <icon wx:else type="circle" class="cart-icon" size="20" bindtap="select" data-index="{{index}}" />
          <text class='checkAll'>select all</text>

          <view class='cart-pay'>
            <text class='cart_pay' bindtap="cleanAll" data-index="{{index}}" data-id="{{item.id}}">All settlement</text>
          </view>

          <view class='cart-sum'>
            <text class='cart_sum'>
              <text class='sum_text'>Total:</text>
              <text class='sum_color'>RMB {{total}}</text>
            </text>
          </view>
        </view>
      </view>
    </view>
  </van-tab>
  <van-tab title="To be shipped">
    <view class="buy__info page2">
      <p>There's no content here</p>
    </view>
  </van-tab>
  <van-tab title="To be received">
    <view class="buy__info page3">
      <p>There's no content here</p>
    </view>
  </van-tab>
  <van-tab title="All Orders">
    <view class="buy__info page4">
      <view class="buy__info_goods" wx:for="{{goods}}" wx:key="index">
        <view class="buy__info_goods_hd">A successful deal</view>
        <van-card price="{{item.price}}" desc="X {{item.value}}" title="{{item.title}}" thumb="{{item.pic}}" />
      </view>
    </view>
  </van-tab>
</van-tabs>
Copy the code

The whole shopping cart operation realizes the purchase quantity calculation, price calculation, check binding and empty record. So how do you get this complex data in different interfaces πŸ‘€?

We all know that different pages get data in applets in one of these ways:

  • The URL passes data with parameters
  • Global variables pass data
  • The local cache passes data

And want to achieve multifunctional so, here, using the wx. SetStorageSync (string key, Object | string data) and url and mix

JS logic code

Submit order button
  pay(e) {
    let goods = wx.getStorageSync("goods") | | []let exist = goods.find((el) = > {
      console.log(e);
      return el.id == this.data.id
    })
    // console.log(e);
    // If the item is in the cart, the quantity increases by one each time
    if (exist) {
      exist.value = parseInt(exist.value) + 1
    } else {
      goods.push({
        id: this.data.id,
        title: e.target.dataset.title,
        pic: e.target.dataset.pic,
        price: e.target.dataset.price,
        value: 1.selected: true})}// console.log(goods);
    // Update cached data
    wx.setStorageSync("goods", goods)
    wx.showLoading({
      title: 'Submitting order',})setTimeout(function () {
      wx.hideLoading()
      wx.showToast({
        title: 'Submitted successfully'.icon: 'success'.duration: 1000})},1000)
    setTimeout(function () {
      wx.switchTab({
        url: '.. /buy/buy',}}),1500)},Copy the code

Click the Submit order button, wx.getStoragesync (“goods”) creates the key and determines whether the item exists in the cart. If so, quantity +1; if not, goods. Push, and updates the cached data.

Shopping cart basic business logic
const db = wx.cloud.database()
const dewuCollection = db.collection('dewu')

Page({
  data: {
    goods: [].total: 0.CheckAll: false
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: 'My Purchase'})},onShow() {
    let goods = wx.getStorageSync("goods")
    this.setData({
      cartList: false.goods: goods
    })
    console.log(goods); }})Copy the code

Note here that this.setData should be placed in onShow(), not onLoad because we want to load storage data every time we enter this page.

Select all items
  // Select all items
  select(e) {
    let CheckAll = this.data.CheckAll; CheckAll = ! CheckAlllet goods = this.data.goods

    for (let i = 0; i < goods.length; i++) {
      goods[i].selected = CheckAll
    }

    this.setData({
      goods: goods,
      CheckAll: CheckAll
    })
    this.getTotal()
  }
Copy the code
Select designated goods
  // Select the item
  selectedCart(e) {
    var goods = this.data.goods // Get the shopping cart list
    var index = e.currentTarget.dataset.index; // Gets the index of the current clicked event
    var selected = goods[index].selected; // Get the value in the shopping cart

    / / the notgoods[index].selected = ! selected;this.setData({
      goods: goods
    })
    this.getTotal();
    wx.setStorageSync("goods", goods)
  }
Copy the code

We can use the e.c. with our fabrication: urrentTarget. Dataset. Subscript index in the index for the click event, and then goods [index]. Selected to obtain the value value of the shopping cart inside

Delete the goods
  / / delete
  delete(e) {
    let goods = this.data.goods // Get the shopping cart list
    let index = e.currentTarget.dataset.index // Gets the index of the current clicked event
    goods.splice(index, 1)
    this.setData({
      goods: goods
    });
    if (goods.length) {
      this.setData({
        cartList: false
      });
    }
    this.getTotal()
    wx.setStorageSync("goods", goods)
  }
Copy the code

Splice (index, 1) to delete goods

Calculate the total price
/ / total
  getTotal() {
    let sum = 0
    for (let i = 0; i < this.data.goods.length; i++) {
      if (this.data.goods[i].selected) {
        sum += this.data.goods[i].value * this.data.goods[i].price
      }
    }
    // Update data
    this.setData({
      total: sum
    })
  }
Copy the code

Finally the most important calculation of commodity prices came, later is not afraid to buy a gift to his girlfriend over 😘

Advice for everyone

If you have a bug in your project, break console.log() as often as possible to see if you have a problem. If there is no error but the data is not available, check for spelling errors in direct calls. When dealing with complex business logic, think it through before you start. When designing the web page, read more about wechat app development documentation and Vant Vant appellate.

Source code of this project

You can get it from Gitee if you need it.

conclusion

Experienced the cooperation of the development of the program ape should have the same feeling, project development should be a happy thing, but the problem came again, before just personal development projects ah, document writing, drawing, they can understand, the most important is to write code, the software design can be completed everything. But by working together now, not on your own project, you can create a good project. Many thanks to my teachers and classmates who helped me in the process of writing the project. If you like this article or see something helpful here, please like it at 😺!