包河车速汽车服务 發表於 2021-10-27 22:03:00

支付宝小程序开发准备工作

<p>在正式开发支付宝小程序之前,我们要做一些准备工作,比如说封装一下config文件、request请求、api接口集中定义,自定义的工具脚本等。文末还有彩蛋哈~</p>
<p>第一步:在支付宝开发者工具中新增支付宝小程序。</p>
<p>第二步:在小程序文件的根目录创建utils目录。</p>
<p>创建自定义的相关js文件(或者直接从以前定义好的项目中拷贝过来),如apis.js、config.js、tools.js、http.js、tools.sjs</p>
<p>1.小程序中调用接口的集中展示,加上备注信息,这样在后台查看的时候方便一些吧。</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">apis.js</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">此处为封装的请求方法</span>
import { getJSON } from './http'<span style="color: rgba(0, 0, 0, 1)">


const apis </span>=<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 用户登录</span>
    userLogin(params, method = 'GET'<span style="color: rgba(0, 0, 0, 1)">) {
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> getJSON('/api/login?r=' + <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Date().getTime(), params, method)
    },</span><span style="color: rgba(0, 0, 0, 1)">
}

module.exports </span>= apis</pre>
</div>
<p>&nbsp;</p>
<p> 2.配置文件,开发的时候难免遇到接口地址切换开发环境、测试环境、生产环境等各种环境,我们事先配置好文件,在切换的时候直接修改环境参数即可。</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 后台不同环境</span>
const ENV =<span style="color: rgba(0, 0, 0, 1)"> {
    SIT: </span>'sit'<span style="color: rgba(0, 0, 0, 1)">,
    UAT: </span>'uat'<span style="color: rgba(0, 0, 0, 1)">,
    PRD: </span>'prd'<span style="color: rgba(0, 0, 0, 1)">
};

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">后台环境对应的接口目录</span>
const BUILD_INFO =<span style="color: rgba(0, 0, 0, 1)"> {
    sit: {
      api: </span>'http://127.0.0.1:8080'<span style="color: rgba(0, 0, 0, 1)">,
      domain: </span>''<span style="color: rgba(0, 0, 0, 1)">
    },
    uat: {
      api: </span>'https://**.com'<span style="color: rgba(0, 0, 0, 1)">,
      domain: </span>'https://**.com'<span style="color: rgba(0, 0, 0, 1)">
    },
    prd: {
      api: </span>'https://**.com'<span style="color: rgba(0, 0, 0, 1)">,
      domain: </span>'https://**.com'<span style="color: rgba(0, 0, 0, 1)">
    }
}
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 小程序APP_id</span>
const APP_ID =<span style="color: rgba(0, 0, 0, 1)"> {
    sit: </span>''<span style="color: rgba(0, 0, 0, 1)">,
    uat: </span>''<span style="color: rgba(0, 0, 0, 1)">,
    prd: </span>''<span style="color: rgba(0, 0, 0, 1)">
}

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 不同环境的版本</span>
const VERSION =<span style="color: rgba(0, 0, 0, 1)"> {
    sit: </span>'1.2.1'<span style="color: rgba(0, 0, 0, 1)">,
    uat: </span>'1.0.1'<span style="color: rgba(0, 0, 0, 1)">,
    prd: </span>'1.0.16'<span style="color: rgba(0, 0, 0, 1)">
}

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">实际使用的后台环境</span>
const env =<span style="color: rgba(0, 0, 0, 1)"> ENV.PRD;

const config </span>=<span style="color: rgba(0, 0, 0, 1)"> {
    ENV: env,
    API_URL: BUILD_INFO.api,
    APP_ID: APP_ID,
    DOMAIN_URL: BUILD_INFO.domain,
    VERSION: VERSION
};

module.exports </span>= config;</pre>
</div>
<p>&nbsp;</p>
<p> 3.封装一些常用的工具函数以便我们提升开发效率。比如小程序中的页面跳转一般情况下要绑定事件,然后定义事件方法,在其中定义跳转的页面,此处我封装了一个go2page的方法,这样就不用在小程序页面的脚本中定义各种跳转事件了。不过就是需要在引用go2page的地方添加参数到data中。</p>
<p>在使用go2page方法进行页面跳转后,我们需要从query中提取参数。使用下面的curPagePath方法即可。</p>
<div class="cnblogs_code">
<pre>const tools =<span style="color: rgba(0, 0, 0, 1)"> {
    isObject(obj) {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (Object.prototype.toString.call(obj) === ''<span style="color: rgba(0, 0, 0, 1)">) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
      }
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
    },
    isDefine(str) {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (str === 0<span style="color: rgba(0, 0, 0, 1)">) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
      }
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (str == '' || (!<span style="color: rgba(0, 0, 0, 1)">str)) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
      }
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
    },
    isIDCard(str) {
      const reg </span>= /^(^\d{7}((0\d)|(1))((\d)|3)\d{3}$)|(^\d{5}\d{3}((0\d)|(1))((\d)|3)((\d{4})|\d{3})$)$/
      <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> reg.test(str)
    },
    isPhone(str) {
      const myreg </span>= /^1\d{8}$/
      <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> myreg.test(str)
    },
    isFullName(str) {
      const reg </span>= /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/
      <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> reg.test(str)
    },
    getUrlParam(href) {
      const indexWen </span>= href.indexOf('?'<span style="color: rgba(0, 0, 0, 1)">)
      const indexJing </span>= href.indexOf('#'<span style="color: rgba(0, 0, 0, 1)">)
      const theRequest </span>=<span style="color: rgba(0, 0, 0, 1)"> {}
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (indexWen === -1<span style="color: rgba(0, 0, 0, 1)">) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> theRequest
      }

      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (indexJing &lt; indexWen) { <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 如果#号在问好前面</span>
            href = href.substring(indexWen + 1<span style="color: rgba(0, 0, 0, 1)">)
      } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
            href </span>= href.substring(indexWen + 1<span style="color: rgba(0, 0, 0, 1)">, indexJing)
      }
      const strArr </span>= href.split('&amp;'<span style="color: rgba(0, 0, 0, 1)">)
      </span><span style="color: rgba(0, 0, 255, 1)">for</span> (let i = 0; i &lt; strArr.length; i++<span style="color: rgba(0, 0, 0, 1)">) {
            theRequest.split(</span>'=')] = unescape(strArr.split('='))
      }
      </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> theRequest
    },
    stringifyParam(param </span>=<span style="color: rgba(0, 0, 0, 1)"> {}) {
      let paramString </span>= ''
      <span style="color: rgba(0, 0, 255, 1)">for</span> (let key <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> param) {
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> (paramString === ''<span style="color: rgba(0, 0, 0, 1)">) {
                paramString </span>+= key + '=' +<span style="color: rgba(0, 0, 0, 1)"> param
            } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
                paramString </span>+= '&amp;' + key + '=' +<span style="color: rgba(0, 0, 0, 1)"> param
            }
      }
      </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> paramString
    },
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 生成随机码</span>
<span style="color: rgba(0, 0, 0, 1)">    getRandom(num) {
      const </span><span style="color: rgba(0, 0, 255, 1)">char</span> = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'<span style="color: rgba(0, 0, 0, 1)">
      const result </span>=<span style="color: rgba(0, 0, 0, 1)"> []
      </span><span style="color: rgba(0, 0, 255, 1)">for</span> (let i = 0; i &lt; num - 1; i++<span style="color: rgba(0, 0, 0, 1)">) {
            const index </span>= Math.random() * <span style="color: rgba(0, 0, 255, 1)">char</span>.length - 1<span style="color: rgba(0, 0, 0, 1)">
            const value </span>= <span style="color: rgba(0, 0, 255, 1)">char</span><span style="color: rgba(0, 0, 0, 1)">.charAt(index)
            result.push(value)
      }
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> result.join(''<span style="color: rgba(0, 0, 0, 1)">)
    },
    desensitizing(str </span>= '', from = 0, length = 0, replaceStr = '*') { <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 隐藏某些字符串</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span> (str.length === 0<span style="color: rgba(0, 0, 0, 1)">) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
      }
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 变成数组</span>
      const strArr = str.split(''<span style="color: rgba(0, 0, 0, 1)">)
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 更改数组</span>
<span style="color: rgba(0, 0, 0, 1)">      strArr.splice(from, length, replaceStr.repeat(length))
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> strArr.join(''<span style="color: rgba(0, 0, 0, 1)">)
    },
    htmlEncode(str </span>= ''<span style="color: rgba(0, 0, 0, 1)">) {
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (str === ''<span style="color: rgba(0, 0, 0, 1)">) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
      }
      let s </span>= str.replace(/&amp;/g, '&amp;'<span style="color: rgba(0, 0, 0, 1)">)
      s </span>= s.replace(/&lt;/g, '&lt;'<span style="color: rgba(0, 0, 0, 1)">)
      s </span>= s.replace(/&gt;/g, '&gt;'<span style="color: rgba(0, 0, 0, 1)">)
      s </span>= s.replace(/\'/g, '''<span style="color: rgba(0, 0, 0, 1)">)
      s = s.replace(/\"/g, </span>'"<span style="color: rgba(0, 0, 0, 1)">')
      return s
    },
    getDay(day) {
      var today = new Date();
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds); //注意,这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.doHandleMonth(tMonth + 1);
      tDate = this.doHandleMonth(tDate);
      return tYear + </span>"-" + tMonth + "-"<span style="color: rgba(0, 0, 0, 1)"> + tDate;
    },
    doHandleMonth(month) {
      var m = month;
      if (month.toString().length == 1) {
            m = </span>"0"<span style="color: rgba(0, 0, 0, 1)"> + month;
      }
      return m;
    },
    getWeek(dateString) {
      var dateArray = dateString.split(</span>"-"<span style="color: rgba(0, 0, 0, 1)">);
      var date = new Date(dateArray, parseInt(dateArray - 1), dateArray);
      return </span>"周" + "日一二三四五六"<span style="color: rgba(0, 0, 0, 1)">.charAt(date.getDay());
    },
    getUserInfo() {
      my.getStorage({
            key: 'userInfo',
            success: function (res) {
                console.log('获取缓存中用户信息', res)
                return res.data
            },
            fail: function (res) {
                console.log('获取缓存中用户信息失败', res)
                return {}
            }
      });

    },
    checkToken(callback, param = {}) {
      let that = this
      var app = getApp()
      if (app.globalData.userId) {
            callback.call(this, param);
      } else {
            setTimeout(function () {
                param = Object.assign(param, app.globalData)
                that.checkToken(callback, param);
            }, 200);
      }
    },
    go2page(e) {
      const { dataset } = e.target
      let params = []
      for (let key in dataset) {
            if (key != 'url') {
                params.push(key + '=' + dataset)
            }
      }
      if (!this.isDefine(e.target.dataset.url)) {
            my.showToast({
                type: 'success',
                content: '建设中,敬请期待',
                duration: 3000,
                success: () =&gt; {
                },
            });
      } else {
            let url = e.target.dataset.url
            if (params.length &gt; 0) {
                url = url + '?' + params.join('&amp;')
            }

            my.navigateTo({
                url: url
            });
      }
    },
    round(str) {
      if(!str){return ''}
      return str.toFixed(2)
    },
    curPagePath(query){
      let pages = getCurrentPages();
      let currPage = null;
      // console.log(pages) 的到一个数组
      if (pages.length) {
      // 获取当前页面的对象(上边所获得的数组中最后一项就是当前页面的对象)
      currPage = pages;
      }
      // 获取当前页面的路由
      let route = currPage.route
      let params = []
      if(query){
            for (let key in query) {
                params.push(key + '=' + query)
            }
      }
      if(params.length&gt;0){
            route += '?' + params.join('&amp;')
      }
      console.log('当前页面路径==&gt;',route)
    },
    getTimeList(start, end, step,restStart,restEnd,selectDate) {
      var curDate = new Date(),
            curFullYear = curDate.getFullYear(),
            curMonth = curDate.getMonth() + 1,
            curDay = curDate.getDate()
      curMonth = curMonth &lt; 10 ? '0' + curMonth : curMonth
      curDay = curDay &lt; 10 ? '0' + curDay : curDay
      var ymd = curFullYear + '/' + curMonth + '/' + curDay
      selectDate = selectDate.replace(/-/g,'/')

      console.log('selectDate',selectDate)

      var startTime = new Date(ymd + ' ' + start).getTime(),
            endTime = new Date(ymd + ' ' + end).getTime(),
            restStartTime = new Date(ymd + ' ' + restStart).getTime(),
            restEndTime = new Date(ymd + ' ' + restEnd).getTime()
      var returnArr = []
      while (startTime + step * 60 * 1000 &lt;= endTime) {
            // 中途休息的时间阶段
            if(startTime + step * 60 * 1000&gt;restStartTime &amp;&amp; startTime + step * 60 * 1000&lt;=restEndTime){
                startTime += step * 60 * 1000
                continue
            }
            // 如果时间小于当前时间则跳过显示
            if(startTime + step * 60 * 1000&lt;new Date().getTime() &amp;&amp; ymd == selectDate){
                startTime += step * 60 * 1000
                continue
            }
            returnArr.push(this.getTime(startTime) + '-' + this.getTime(startTime+step*60*1000))
            startTime += step * 60 * 1000
      }

      return returnArr

    },

    getTime(timestamp) {
      var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 &lt; 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() &lt; 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() &lt; 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = (date.getMinutes() &lt; 10 ? '0' + date.getMinutes() : date.getMinutes()) + '';
      var s = date.getSeconds() &lt; 10 ? '0' + date.getSeconds() : date.getSeconds();
      return h + m;
    },
    isIphoneX(){
      var u = navigator.userAgent;
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isIOS) {
            if (screen.height == 812 &amp;&amp; screen.width == 375) {
                return true;
            }
            else {
                return false;
            }
      }
    }

}
module.exports = tools;</span></pre>
</div>
<p>&nbsp;</p>
<p>4.常用的请求方法,根据实际项目中约定的接口规范进行修改。</p>
<div class="cnblogs_code">
<pre>import config from './config'<span style="color: rgba(0, 0, 0, 1)">;

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> isApiSuccess(result) {
    const status </span>= result.success || result.stat || result.status || ''; <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 接口状态字段</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> (status == <span style="color: rgba(0, 0, 255, 1)">true</span> || status == '000' || status === 'ok' || status === 'success' || status === 'succeed'<span style="color: rgba(0, 0, 0, 1)">) {
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">;
    }
}

export </span><span style="color: rgba(0, 0, 255, 1)">function</span> getJSON(url, params, method = 'GET', mockSetting =<span style="color: rgba(0, 0, 0, 1)"> {}) {
    let path </span>= ''<span style="color: rgba(0, 0, 0, 1)">;
    const { on </span>= <span style="color: rgba(0, 0, 255, 1)">false</span>, mockData = {} } =<span style="color: rgba(0, 0, 0, 1)"> mockSetting;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (url.indexOf('http') &gt; -1 || url.indexOf('https') &gt; -1<span style="color: rgba(0, 0, 0, 1)">) {
      path </span>=<span style="color: rgba(0, 0, 0, 1)"> url;
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
      path </span>= config.API_URL +<span style="color: rgba(0, 0, 0, 1)"> url;
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span> Promise((resolve, reject) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      my.showLoading();
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (on) {
            console.log(</span>'-------返回 mock 数据-------'<span style="color: rgba(0, 0, 0, 1)">, url, params, mockData);
            </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (isApiSuccess(mockData)) {
                resolve(mockData);
            } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
                reject(mockData);
            }
            my.hideLoading();
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)">;
      }

      let token </span>=<span style="color: rgba(0, 0, 0, 1)"> params.token
      let headers </span>=<span style="color: rgba(0, 0, 0, 1)"> {
            </span>"Content-Type": "application/json"<span style="color: rgba(0, 0, 0, 1)">,
      }

      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (params.headers) {
            headers </span>=<span style="color: rgba(0, 0, 0, 1)"> Object.assign(headers, params.headers)
            </span><span style="color: rgba(0, 0, 255, 1)">delete</span><span style="color: rgba(0, 0, 0, 1)"> params.headers
      }
      </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (token) {
            headers[</span>'Authorization'] = 'Bearer ' +<span style="color: rgba(0, 0, 0, 1)"> token
            </span><span style="color: rgba(0, 0, 255, 1)">delete</span><span style="color: rgba(0, 0, 0, 1)"> params.token
      }
      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (method.toLocaleLowerCase() != 'get'<span style="color: rgba(0, 0, 0, 1)">) {
            headers[</span>'content-type'] = 'application/json'<span style="color: rgba(0, 0, 0, 1)">
      }

      </span><span style="color: rgba(0, 0, 255, 1)">if</span> (method.toLocaleLowerCase() == 'delete'<span style="color: rgba(0, 0, 0, 1)">) {
            headers[</span>'content-type'] = 'application/x-www-form-urlencoded'<span style="color: rgba(0, 0, 0, 1)">
      }

      my.request({
            url: path,
            method: method,
            data: params,
            dataType: </span>'json'<span style="color: rgba(0, 0, 0, 1)">,
            headers: headers,
            success: (result) </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> console.log(`--返回数据--接口地址=&gt;${url},结果=&gt;${JSON.stringify(result)}`);</span>
<span style="color: rgba(0, 0, 0, 1)">                my.hideLoading();
                </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (isApiSuccess(result.data)) {
                  resolve(result.data);
                } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
                  reject(result.data);
                }
            },
            fail: (err) </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
                console.log(</span>'-------返回错误-------'<span style="color: rgba(0, 0, 0, 1)">, url, err);
                my.hideLoading();
                </span><span style="color: rgba(0, 0, 255, 1)">if</span> (err.status == 401<span style="color: rgba(0, 0, 0, 1)">) {
                  console.log(</span>'未登录权限'<span style="color: rgba(0, 0, 0, 1)">)
                }
                my.showToast({
                  type: </span>'fail'<span style="color: rgba(0, 0, 0, 1)">,
                  content: </span>'请求异常,请稍后再试!'<span style="color: rgba(0, 0, 0, 1)">
                });
                reject(err);
            },
      });
    });
}</span></pre>
</div>
<p>&nbsp;</p>
<p>5.在页面中引用方法时需要用到sjs文件。</p>
<div class="cnblogs_code">
<pre>const desensitizing = (str,from,length,replaceStr = '*')=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (str.length === 0<span style="color: rgba(0, 0, 0, 1)">) {
      </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
    }
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 变成数组</span>
    const strArr = str.split(''<span style="color: rgba(0, 0, 0, 1)">)
    let replace_str </span>= ''
    <span style="color: rgba(0, 0, 255, 1)">for</span>(<span style="color: rgba(0, 0, 255, 1)">var</span> i=0;i&lt;length;i++<span style="color: rgba(0, 0, 0, 1)">){
      replace_str </span>+=<span style="color: rgba(0, 0, 0, 1)"> replaceStr
    }
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 更改数组</span>
<span style="color: rgba(0, 0, 0, 1)">    strArr.splice(from, length, replace_str)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> strArr.join(''<span style="color: rgba(0, 0, 0, 1)">)
}
const repeat </span>= (length,repeatStr='*') =&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> str = ''
    <span style="color: rgba(0, 0, 255, 1)">for</span>(let i=0;i&lt;length;i++<span style="color: rgba(0, 0, 0, 1)">){
      str </span>+=<span style="color: rgba(0, 0, 0, 1)"> repeatStr
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
}
const desensitizing2 </span>= (str,type,isdes=<span style="color: rgba(0, 0, 255, 1)">false</span>,replaceStr = '*')=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(!<span style="color: rgba(0, 0, 0, 1)">isdes){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
    }
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str == '' || !<span style="color: rgba(0, 0, 0, 1)">str){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> ''<span style="color: rgba(0, 0, 0, 1)">
    }
    </span><span style="color: rgba(0, 0, 255, 1)">switch</span><span style="color: rgba(0, 0, 0, 1)">(type){
      </span><span style="color: rgba(0, 0, 255, 1)">case</span> 'name'<span style="color: rgba(0, 0, 0, 1)">:
            str </span>= str.replace(getRegExp('·','g'<span style="color: rgba(0, 0, 0, 1)">),replaceStr);
            </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str.length == 1<span style="color: rgba(0, 0, 0, 1)">){
                </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> replaceStr
            }
            </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str.length&gt;=2<span style="color: rgba(0, 0, 0, 1)">){
                </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str.length&gt;=5<span style="color: rgba(0, 0, 0, 1)">){
                  </span><span style="color: rgba(0, 0, 255, 1)">return</span> repeat(4,replaceStr) + str
                }
                </span><span style="color: rgba(0, 0, 255, 1)">return</span> desensitizing(str,0,str.length-1<span style="color: rgba(0, 0, 0, 1)">)
            }
            </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> replaceStr;
            </span><span style="color: rgba(0, 0, 255, 1)">break</span><span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 0, 255, 1)">case</span> 'sfz'<span style="color: rgba(0, 0, 0, 1)">:
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> desensitizing(str,1,str.length-2<span style="color: rgba(0, 0, 0, 1)">)
            </span><span style="color: rgba(0, 0, 255, 1)">break</span><span style="color: rgba(0, 0, 0, 1)">;
      </span><span style="color: rgba(0, 0, 255, 1)">case</span> 'phone'<span style="color: rgba(0, 0, 0, 1)">:
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> desensitizing(str,3,6<span style="color: rgba(0, 0, 0, 1)">)
            </span><span style="color: rgba(0, 0, 255, 1)">break</span><span style="color: rgba(0, 0, 0, 1)">;
    }
}

const substring </span>= (str,from,length=0)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str.length == 0<span style="color: rgba(0, 0, 0, 1)">){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> ''<span style="color: rgba(0, 0, 0, 1)">
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> str.substring(from,from+<span style="color: rgba(0, 0, 0, 1)">length)
}
const isDefine </span>= (str)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (str === '' || !<span style="color: rgba(0, 0, 0, 1)">str) {
            </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">
}
const round </span>= (str,len=2)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(!str){<span style="color: rgba(0, 0, 255, 1)">return</span> ''<span style="color: rgba(0, 0, 0, 1)">}
    let point_index </span>= str.lastIndexOf('.'<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(len == 0<span style="color: rgba(0, 0, 0, 1)">){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> str.substring(0,1<span style="color: rgba(0, 0, 0, 1)">)
    }
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str.length &gt; len + point_index + 1<span style="color: rgba(0, 0, 0, 1)">){
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> str.substring(0,len + point_index + 1<span style="color: rgba(0, 0, 0, 1)">)
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> str
}
const str2date </span>= (str,separater='-') =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(str === '' || !str || str.length&lt;8<span style="color: rgba(0, 0, 0, 1)">) {
      </span><span style="color: rgba(0, 0, 255, 1)">return</span> ''<span style="color: rgba(0, 0, 0, 1)">
    }

    </span><span style="color: rgba(0, 0, 255, 1)">return</span> str.substring(0,4) + separater + str.substring(4,6) + separater + str.substring(6,8<span style="color: rgba(0, 0, 0, 1)">)

}
export </span><span style="color: rgba(0, 0, 255, 1)">default</span><span style="color: rgba(0, 0, 0, 1)"> {
    desensitizing,
    substring,
    isDefine,
    round,
    desensitizing2,
    str2date
}</span></pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;以上准备工作完成之后,需要引用一下支付宝小程序的ui组件,我用的是<code>mini-ali-ui。</code></p>
<p>&nbsp;这下终于可以开发愉快地写页面了吧。此时此刻你在想什么呢。</p>
<p>作为一个经常使用mac、linux系统的程序猿,想借助于开发工具中的控制台进行页面创建,怎么办呢?</p>
<p>这时候要用到node的功能了,在根目录下添加package.json</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">{
</span>"dependencies"<span style="color: rgba(0, 0, 0, 1)">: {
    </span>"iconv-lite": "^0.6.3"<span style="color: rgba(0, 0, 0, 1)">
},
</span>"scripts"<span style="color: rgba(0, 0, 0, 1)">: {
    </span>"page": "node scripts/page"<span style="color: rgba(0, 0, 0, 1)">
}
}</span></pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;然后在根目录添加scripts目录,在scripts目录中添加page.js</p>
<p>示例代码如下:此程序仅支持 “pages/分组名称/页面名称”这种结构的页面创建,若需要减小层级或增加层级自行修改哈。</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">*
* pages页面快速生成脚本
* 用法:npm run tep `文件名`
* npm run page product/ProductClass
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">

const fs </span>= require('fs'<span style="color: rgba(0, 0, 0, 1)">);
</span><span style="color: rgba(0, 0, 255, 1)">var</span> iconv = require('iconv-lite'<span style="color: rgba(0, 0, 0, 1)">);

const dirName </span>= process.argv;
const cover </span>= process.argv;
console.log(dirName)
const dirNameArr </span>= dirName.split('/'<span style="color: rgba(0, 0, 0, 1)">)
const folder </span>= dirNameArr
const fileName </span>= dirNameArr
const capPirName </span>= dirName.substring(0, 1).toUpperCase() + dirName.substring(1<span style="color: rgba(0, 0, 0, 1)">);
console.log(folder, fileName, capPirName, __dirname)
</span><span style="color: rgba(0, 0, 255, 1)">if</span> (!<span style="color: rgba(0, 0, 0, 1)">dirName) {
    console.log(</span>'文件夹名称不能为空!'<span style="color: rgba(0, 0, 0, 1)">);
    console.log(</span>'示例:npm run page product/ProductClas'<span style="color: rgba(0, 0, 0, 1)">);
    process.exit(</span>0<span style="color: rgba(0, 0, 0, 1)">);
}

</span><span style="color: rgba(0, 0, 255, 1)">var</span> curPath = __dirname.substring(0, __dirname.lastIndexOf('/'<span style="color: rgba(0, 0, 0, 1)">))
console.log(</span>'curPath=='<span style="color: rgba(0, 0, 0, 1)">, curPath)

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> loadjson(filepath) {
    </span><span style="color: rgba(0, 0, 255, 1)">var</span><span style="color: rgba(0, 0, 0, 1)"> data;
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 0, 255, 1)">var</span> jsondata = iconv.decode(fs.readFileSync(curPath + '/' + filepath, "binary"), "utf8"<span style="color: rgba(0, 0, 0, 1)">);
      data </span>=<span style="color: rgba(0, 0, 0, 1)"> JSON.parse(jsondata);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (err) {
      console.log(err);
    }

    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> data;
}


</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> savejson(filepath, data) {
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> datastr = JSON.stringify(data, <span style="color: rgba(0, 0, 255, 1)">null</span>, 4<span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (datastr) {
      </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
            fs.writeFileSync(curPath </span>+ '/' +<span style="color: rgba(0, 0, 0, 1)"> filepath, datastr);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (err) {

      }
    }
}

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">model模板</span>
<span style="color: rgba(0, 0, 0, 1)">
const wxmlTemp </span>=<span style="color: rgba(0, 0, 0, 1)"> `
    </span>&lt;view&gt;
    &lt;/view&gt;
<span style="color: rgba(0, 0, 0, 1)">`
const jsTemp </span>=<span style="color: rgba(0, 0, 0, 1)"> `
import tools from </span>'/utils/tools'<span style="color: rgba(0, 0, 0, 1)">
import { getJSON } from </span>'/utils/http'<span style="color: rgba(0, 0, 0, 1)">
import apis from </span>'/utils/apis'<span style="color: rgba(0, 0, 0, 1)">
const app </span>=<span style="color: rgba(0, 0, 0, 1)"> getApp()
Page({

    data: {

    },

    onLoad: </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> (options) {
      tools.curPagePath(options)
    },

    onShow: </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> () {

    },
    go2page(e){
      tools.go2page(e)
    }
})
`
const wxssTemp </span>=<span style="color: rgba(0, 0, 0, 1)"> `

`
const jsonTemp </span>=<span style="color: rgba(0, 0, 0, 1)"> `
{
    </span>"usingComponents"<span style="color: rgba(0, 0, 0, 1)">: {}
}
`
</span><span style="color: rgba(0, 0, 255, 1)">if</span> (!fs.existsSync(`pages/${folder}`)) {
    fs.mkdirSync(`pages/${folder}`)
<span style="color: rgba(0, 0, 0, 1)">}

</span><span style="color: rgba(0, 0, 255, 1)">if</span> (!fs.existsSync(`pages/${folder}/<span style="color: rgba(0, 0, 0, 1)">${fileName}`)) {
    fs.mkdirSync(`pages</span>/${folder}/<span style="color: rgba(0, 0, 0, 1)">${fileName}`)
} </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 如果文件夹存在则说明页面已创建,不能再操作了,否则会覆盖已有页面</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> (cover &amp;&amp; cover != 1<span style="color: rgba(0, 0, 0, 1)">) {
      process.exit(</span>0<span style="color: rgba(0, 0, 0, 1)">);
    }
}
</span><span style="color: rgba(0, 0, 0, 1)">
process.chdir(`pages</span>/${folder}/${fileName}`); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> cd $1</span>
<span style="color: rgba(0, 0, 0, 1)">

fs.writeFileSync(`${fileName}.axml`, wxmlTemp)
fs.writeFileSync(`${fileName}.json`, jsonTemp)
fs.writeFileSync(`${fileName}.acss`, wxssTemp)
fs.writeFileSync(`${fileName}.js`, jsTemp)

</span><span style="color: rgba(0, 0, 255, 1)">var</span> jsonPath = 'app.json'
<span style="color: rgba(0, 0, 255, 1)">var</span> appJson =<span style="color: rgba(0, 0, 0, 1)"> loadjson(jsonPath)
</span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (appJson) {
    </span><span style="color: rgba(0, 0, 255, 1)">var</span> pages =<span style="color: rgba(0, 0, 0, 1)"> appJson.pages
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (pages.indexOf(`pages/${folder}/${fileName}/${fileName}`) == -1) {
      pages.push(`pages/${folder}/${fileName}/${fileName}`)
<span style="color: rgba(0, 0, 0, 1)">    }

    savejson(jsonPath, appJson)


}

process.exit(</span>0);</pre>
</div>
<p>终于写完了,以上是我个人在开发支付宝小程序时的经验总结,仅供参考。不喜可以直接跳过~~~</p><br><br>
来源:https://www.cnblogs.com/dzlishen/p/15473190.html
頁: [1]
查看完整版本: 支付宝小程序开发准备工作