Do not miscutter work, in the development of a good preparation can greatly improve the efficiency of development, reduce redundant code, this article combined with their own experience to do a summary of several small procedures.


For more information, see “Validated” Apps – Developing Process Guidelines

What do you have to do before you start developing small programs?

  • Rewrite the Page, Component functions of the applet
  • Request method encapsulation
  • Router Encapsulation
  • The use of Less
  • Util encapsulation

Why rewrite the Page/Component function?

Have you ever experienced this before getting ready to develop a page…

import store from ".. /utils/store";
import util from ".. /utils/util";
import fetch from ".. /utils/fetch";
import config from ".. /utils/config";

Page ({
  // ...  
})
Copy the code

Copy and paste each page I @#$%^&*


The following solutions may solve these problems and be quite comfortable

  1. Create init.js and import it into app.js, like ⬇️
require('./utils/Init.js');

App({
  onLaunch: function() {}})Copy the code
  1. Rewrite the Page, Component functions

Function rewrite thinking: applet belongs to single Page application, global Page Component registration depends on Page, Component function, in fact, is called a function passed in an object, so can we do some minor action before the function call?

Let’s try it out

Edit the Init. Js

// function hijacking overwrites the registration functionletoriginPage = Page; Page = (opt) => {// Add an util object opt.util = {to the argument passed to Page.test () {
            return1; }}return originPage(opt);
}
Copy the code

Test this in the page onLoad method

Page({
  data: {
  },
  onLoad: function () {
    console.log(this.util.test())
  }
})
Copy the code

The output is as follows

The output

Run successfully! Next thing you know what I mean plug him!

Edit the Init. Js

import _store from "./store";
import _util from "./util";
import _fetch from "./fetch";

letoriginPage = Page; Page = (opt) => {// Add the created utility class to the opt parameter. opt, _store, _util, _fetch }return originPage(opt);
}
Copy the code

Then print the this keyword in the page

B: well… Finally, I don’t have to mess with it


Attention! The Component instance does not have an added object like ⬇️ if you write the same thing in the Component function

// Init.js
import _store from "./store";
import _util from "./util";
import _fetch from "./fetch";

let originComponent = Component;
Component = (opt) => {
    opt.util = {
        test() {
            return1}}return originComponent(opt);
}

------------
// components/img/index.js
Component({
  attached () {
    this.test();
  },
  methods: {
    test() {
      console.log(this.util)
    }
  }
})

Copy the code

The results

But that doesn’t mean I don’t have a way

Edit init.js to override the Component section

Component = (opt) => {// The options of the Component function cannot be inserted directly and can only be dynamically assigned when a lifecycle function is calledlet originAttached = opt.attached || function () {};
  opt.attached = function(e) {
    this.util = {
      a() {
        return1; }};return originAttached.apply(this);
  }
  return originComponent(opt)
}
Copy the code

The results

Finally, after adding the following various utility classes, simply write a request and jump to something like ⬇️

Page({
  data: {
  },
  onLoad: function ({ goodId }) {
    this._fetch({
      url: "getGoods",
      data: { goodId }
    }).then(res => {
      if (res.length) {
        this._router.go("detail", { firstGoodsId: res[0].id })
      }
    })
  }
})
Copy the code


The following is a list of the various packages used at work

Request method encapsulation

Wx. request method encapsulation: request status, error unified processing, with the current context can control all components of the page that require request status

Fetch.js

const host = {
  Dev: "http://test.com"
}

const api = {
  getUserInfo: "...",
  getGoods: "..."
}

export default function ({ url, data, showLoading = false{})let self = this;
  changeFetchState(self, true);
  showLoading && wx.showLoading({ title: showLoading })
  return new Promise((resolve, reject) => {
    const options = {
      url: host.Dev + api[url],
      method: "POST",
      header: { "content-type": "application/json" },
      data,
      success: ({ data }) => {
        resolve(data.data, data);
      },
      fail: err => {
        reject(err);
      },
      complete() {
        changeFetchState(self, false); showLoading && wx.hideLoading(); }}; wx.request(options); })} // Call with the current scope to control the components that the page needs to request statefunction changeFetchState (self, state) {
  self && self.setData({ _fetchState: state });
}
Copy the code

Router Encapsulation

It standardizes route management and parameter transmission, defines routes in the form of {key:value}, and reencapsulates route hop methods for easy invocation.

Router.js

// Route definition const routePath = {"index": "/pages/index/index"."detail": "/pages/detail/index"."service": "/pages/service/index"}; Const tabbar = [const tabbar = ['index'.'service'] const Router = {// Parse:function (data) {
    if(! data)return ' ';
    let tempArr = [];
    for (let key in data) {
      tempArr.push(`${key}=${encodeURIComponent(data[key])`);
    }
    return '? ' + tempArr.join('&');
  },
  go: function (path = 'index', params = null, duration = 0) {
    setTimeout(() => { const isTabbar = tabbar.indexOf(path) == -1; Wx [isTabbar?'navigateTo' : 'switchTab']({
        url: routePath[path] + this.parse(params),
      })
    }, duration * 1000);
  },
  goBack: function (delta = 1, duration) {
    setTimeout(() => {
      wx.navigateBack({ delta })
    }, duration * 1000)
  }
}

export default Router;
Copy the code

The use of Less

NPM install less -g

WebStorm -> Preferences
Tools -> File Watchers -> Create monitor File > Less -> set Output File format to WXSS


Util Common class encapsulation

I usually use these tools: Storage, page address parameter, get the current context, etc. Util is usually not all used in development while writing, the following several examples.

Util.js

/ / Storagefunction getStore (name1, name2) {
  if(! name1)return false;
  let baseStore = wx.getStorageSync(name1);
  if(! baseStore)return false;
  return name2 ? (baseStore[name2] || ' ') : baseStore;
}
function setStore (name, value) {
  if(! name)return false;
  return wx.setStorageSync(name, value);
}
function setStoreChild (name1, name2, value) {
  if(! name1 || ! name2)return false;
  let baseStore = getStore(name1) || {};
  baseStore[name2] = value;
  return setStore(name1, baseStore); } /** * returns the data type @param value * @returns {*} */function getValueType(value) {
  if (typeof value === 'number') return Number;
  if (typeof value === 'string') return String;
  if (typeof value === 'boolean') return Boolean;

  if(value instanceof Object && ! value instanceof Array)return Object;
  if (value instanceof Array) return Array;

  returnnull; } /** * get the current page context * @returns {*} */function getPageContext() {
  var pages = getCurrentPages();
  returnpages[pages.length - 1]; } /** * get the element * @param classItem */function $select(className, cb) {
  const query = wx.createSelectorQuery().in(this)
  query.select(className).boundingClientRect()
  query.selectViewport().scrollOffset()
  query.exec(function (res) {
    cb(className.substr('0') = = =The '#' ? res[0] : res);
  })
}

module.exports = {
  getStore,
  setStore,
  setStoreChild,
  getValueType,
  getPageContext,
  $select
}
Copy the code