磨刀不誤砍柴工,在開發以前作好準備工做能夠大大提高開發效率、減小冗餘代碼,這篇文章結合本身作過的幾個小程序的經驗作一個總結【demo地址】。git
相關參考 vant-weapp、武裝你的小程序——開發流程指南github
準備開發頁面以前你是否經歷過這樣...npm
import store from "../utils/store";
import util from "../utils/util";
import fetch from "../utils/fetch";
import config from "../utils/config";
Page ({
// ...
})
複製代碼
require('./utils/Init.js');
App({
onLaunch: function () {}
})
複製代碼
函數重寫思考:小程序屬於單頁面應用,全局的頁面組件註冊全依靠Page、Component函數,實際上就是調用了一個函數 傳入了一個對象,那咱們能不能在函數調用前,對參數作一些小動做呢?json
編輯Init.js小程序
// 函數劫持 重寫註冊函數
let originPage = Page;
Page = (opt) => {
// 在傳入Page函數的參數中 添加一個util對象
opt.util = {
test () {
return 1;
}
}
return originPage(opt);
}
複製代碼
Page({
data: {
},
onLoad: function () {
console.log(this.util.test())
}
})
複製代碼
運行成功!接下來你應該懂個人意思 塞他!api
編輯Init.jsbash
import _store from "./store";
import _util from "./util";
import _fetch from "./fetch";
let originPage = Page;
Page = (opt) => {
// 把建立好的工具類引入opt參數內
opt = {
...opt,
_store,
_util,
_fetch
}
return originPage(opt);
}
複製代碼
// Init.js
import _store from "./store";
import _util from "./util";
import _fetch from "./fetch";
let originComponent = Component;
Component = (opt) => {
opt.util = {
test() {
return 1
}
}
return originComponent(opt);
}
------------
// components/img/index.js
Component({
attached () {
this.test();
},
methods: {
test() {
console.log(this.util)
}
}
})
複製代碼
Component = (opt) => {
// Component函數的options沒法直接插入參數 只能在某個生命週期函數被調用時動態賦值
let originAttached = opt.attached || function () {};
opt.attached = function(e) {
this.util = {
a() {
return 1;
}
};
return originAttached.apply(this);
}
return originComponent(opt)
}
複製代碼
Page({
data: {
},
onLoad: function ({ goodId }) {
this._fetch({
url: "getGoods",
data: { goodId }
}).then(res => {
if (res.length) {
this._router.go("detail", { firstGoodsId: res[0].id })
}
})
}
})
複製代碼
wx.request方法封裝點:請求狀態、錯誤統一處理,以當前上下文可控制頁面全部須要請求狀態的組件app
Fetch.jsless
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);
})
}
// 以當前做用域調用,可控制頁面須要請求狀態的組件
function changeFetchState (self, state) {
self && self.setData({ _fetchState: state });
}
複製代碼
規範路由管理、傳參,以{key:value}形式定義路由,從新封裝路由跳轉方法,方便調用。xss
Router.js
// 路由定義
const routePath = {
"index": "/pages/index/index",
"detail": "/pages/detail/index",
"service": "/pages/service/index"
};
// 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;
// 若是是tabbar用switchTab方法切換
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;
複製代碼
首先全局安裝less插件 npm install less -g
本身經常使用的工具大概有這幾種:Storage存儲、頁面地址取參、獲取當前上下文等等,一般Util一下也想不全都是在開發中邊用邊寫,如下幾個爲例子。
Util.js
// Storage相關
function 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);
}
/**
* 獲取數據類型
* @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;
return null;
}
/**
* 獲取當前頁面上下文
* @returns {*}
*/
function getPageContext() {
var pages = getCurrentPages();
return pages[pages.length - 1];
}
/**
* 獲取元素
* @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') === '#' ? res[0] : res);
})
}
module.exports = {
getStore,
setStore,
setStoreChild,
getValueType,
getPageContext,
$select
}
複製代碼