先簡單說一下,小程序的結(jié)構(gòu)
如圖所示
1、每個視圖(.wxml)只需要添加對應(yīng)名字的腳本(.js)和樣式(.wxss)就可以了,不需要引用,page下面的腳本以及樣式都是繼承至最外面的app.js , app.wxcss
2、腳本也就是.js文件,他有固定格式:page,是用于獲取數(shù)據(jù)的
3、utils是用來放置數(shù)據(jù)接口的
數(shù)據(jù)訪問,如果懂點ajax,都不是問題,沒啥好講的
微信小程序,因為IDE太爛了,如果代碼再寫得難以閱讀,整個項目就很難維護了。
因為沒有寫過app,不知道在app中數(shù)據(jù)訪問是怎么封裝的
作為一個有3天工作經(jīng)驗的小程序碼農(nóng),覺得如果每個頁面的數(shù)據(jù)都是自己去訪問數(shù)據(jù)接口,那就太不OOP了
然后想到了linq to sql,只取了其中的兩個方法,原本打算用singelordefault,firstordefault的,想想也麻煩,就用了getbyparams,getbyid,根據(jù)條件查找出所有數(shù)據(jù),或者根據(jù)id獲取一條數(shù)據(jù)
直接看方法吧,有點啰嗦了
const API_URL = 'http://localhost:4424/api/' function getApi(url,params){ return new Promise((res,rej)=>{ wx.request({ url:API_URL+'/'+url, data:Object.assign({},params), header:{'Content-Type': 'application/json'}, success:res, fail:rej }) }) } module.exports = { GetByParams(url,page=1,pageSize=20,search = ''){ const params = { start: (page - 1) * pageSize, pageSize: pageSize } return getApi(url, search ? Object.assign(params, { q: search }) : params) .then(res => res.data) }, GetById(url,id){ return getApi(url, id) .then(res => res.data) } }
module.exports = {}是固定寫法,里面寫一個一個的方法,每個方法用,隔開。
我設(shè)置了一個url參數(shù),因為不可能把所有的接口都放在一個conntroller里面,所以url的格式是“conntroller/action”
看一個調(diào)用的栗子吧,就明白怎么用了
const req = require('../../utils/util.js') Page({ data: { imgUrls: [], indicatorDots: true, autoplay: true, interval: 2000, duration: 2000 }, onLoad(){ req.GetByParams('home/homebanner')//看這里 看這里 看這里 .then(d=>this.setData({imgUrls:d,loading:false})) .catch(e=>{ this.setData({imgUrls:[],loading:false}) }) } })
這是index的獲取banner圖的方法,req.GetByParams('home/homebanner'),這里也可以帶參數(shù),也可以空著
在右邊的紅色框里面,我們可以看到請求返回的數(shù)據(jù),也可以在右邊修改數(shù)據(jù),界面會跟隨著變化,這是關(guān)于調(diào)試的事情了,容后再議
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
更多微信小程序 數(shù)據(jù)訪問實例詳解相關(guān)文章請關(guān)注PHP中文網(wǎng)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)