三咨跌、發(fā)起請(qǐng)求
1. scroll-view
可滾動(dòng)視圖區(qū)域庆锦。使用豎向滾動(dòng)時(shí),需要給scroll-view一個(gè)固定高度腔召,通過(guò) WXSS 設(shè)置 height。組件屬性的長(zhǎng)度單位默認(rèn)為px扮惦,2.4.0起支持傳入單位(rpx/px)臀蛛。
scroll-x:允許橫向滾動(dòng)。
scroll-y:允許縱向滾動(dòng)崖蜜。
<!-- 導(dǎo)入wxs文件 --><wxssrc="../../wxs/filter.wxs"module="filter"/><viewclass="container"><scroll-viewscroll-yclass="left"><viewclass="item {{activeIndex===index?'active':''}}"wx:for="{{typeList}}"wx:key="index"bindtap="clickType"data-index="{{index}}"data-id="{{item.Id}}">{{item.Name}}</view></scroll-view><scroll-viewscroll-yclass="right"><viewclass="data"wx:for="{{dataList}}"wx:key="index"><viewclass="title">{{item.Title}}</view><viewclass="flex j-s a-c"style="padding:4px0;color:#333333"><view>{{item.Section.Name}}</view><view>{{filter.formatTime(item.Createtime)}}</view></view></view></scroll-view></view>
2. 發(fā)起請(qǐng)求
//顯示Loadingwx.showLoading({title:'加載中',})//wx對(duì)象發(fā)送ajax請(qǐng)求的方法wx.request({method:'GET',url:'https://bingjs.com:8002/Subject/GetSubjects',data:{section_id:id},//成功后的回調(diào)success:({data})=>{//將獲取到數(shù)據(jù)數(shù)據(jù)賦值給對(duì)應(yīng)的數(shù)組浊仆,并更新到頁(yè)面this.setData({dataList:data})},//完成后的回調(diào)complete:()=>{//關(guān)閉Loadingwx.hideLoading()}})
3. 封裝方法
添加config配置
//導(dǎo)出請(qǐng)求地址根路徑exportconstBASE_URL='https://bingjs.com:8002'
添加utils/request.js文件
//導(dǎo)入請(qǐng)求地址根路徑import{BASE_URL}from'../config/const'//ajax請(qǐng)求的方法exportlet$request=function(method,url,data){returnnewPromise((resolve,reject)=>{//顯示Loadingwx.showLoading({title:'加載中',})//wx對(duì)象發(fā)送ajax請(qǐng)求的方法wx.request({method,url:BASE_URL+url,data,//成功后的回調(diào)success:({data})=>{resolve(data)},//失敗后的回調(diào)fail:(err)=>{reject(err)},//完成后的回調(diào)complete:()=>{//關(guān)閉Loadingwx.hideLoading()}})})}//get-ajax請(qǐng)求的方法exportlet$get=function(url,data){return$request('GET',url,data)}//post-ajax請(qǐng)求的方法exportlet$post=function(url,data){return$request('POST',url,data)}wx.$request=$requestwx.$get=$getwx.$post=$post
添加utils/index.js文件
import'./util'import'./request'import'./msg'
在app.js文件中
import'./utils/index'
4. wxs
新建filter.wxs文件,用于格式化時(shí)間
//定義一個(gè)格式化時(shí)間戳的方法functionformatTime(val){varnow=getDate()//獲取當(dāng)前時(shí)間//根據(jù)時(shí)間戳返回一個(gè)時(shí)間對(duì)象vardate=getDate(parseInt(val))varsec=parseInt((now-date)/1000/60)//返回兩日期相差分鐘if(sec<=5){return'剛剛'}elseif(sec<=60){returnsec+'分鐘前'}elseif(sec<=60*24){returnparseInt(sec/60)+'小時(shí)前'}//超過(guò)一天豫领,顯示具體的日期varyear=date.getFullYear()varmonth=date.getMonth()+1varday=date.getDate()varhour=date.getHours()varminute=date.getMinutes()varsecond=date.getSeconds()//拼接時(shí)間并返回return[year,month,day].map(formatNumber).join('/')+' '+[hour,minute,second].map(formatNumber).join(':')}
//補(bǔ)0方法functionformatNumber(n){n=n.toString()returnn[1]?n:'0'+n}//導(dǎo)出該方法module.exports={formatTime:formatTime};
四抡柿、上拉下拉頁(yè)面
1. 頁(yè)面
<!-- 導(dǎo)入wxs文件 --><wxssrc="../../wxs/filter.wxs"module="filter"/><viewclass="container"><navigatorurl="../details/details?id={{item.Id}}"class="data"wx:for="{{dataList}}"wx:key="index"><viewclass="title">{{item.Title}}</view><viewclass="flex j-s a-c desc"><view>{{item.Section.Name}}</view><view>{{filter.formatTime(item.Createtime)}}</view></view></navigator></view><viewbindtap="click"class="btn_add">+</view>
2. 獲取數(shù)據(jù)的方法
//獲取數(shù)據(jù)信息的方法asyncgetDataList(){//參數(shù)pageSize是每頁(yè)顯示數(shù)量,pageIndex是頁(yè)碼letdataList=awaitwx.$get('/Subject/GetSubjects',{pageSize:15,pageIndex:this.data.pageIndex})//判斷如果是首頁(yè)等恐,清空之前數(shù)組中的數(shù)據(jù)if(this.data.pageIndex===1)this.data.dataList=[]//判斷本次查詢洲劣,是否獲取到了數(shù)據(jù)if(!dataList||dataList.length===0)returnwx.$msg('沒(méi)有更多')//更新數(shù)組數(shù)據(jù)this.setData({//用之前數(shù)組里面保存的數(shù)據(jù)去拼接最新的數(shù)據(jù)dataList:this.data.dataList.concat(dataList)})}
3. 下拉刷新
.json文件中設(shè)置允許下拉刷新
"enablePullDownRefresh": true
onPullDownRefresh:function(){//當(dāng)前頁(yè)回到首頁(yè)this.data.pageIndex=1//重新調(diào)用加載數(shù)據(jù)的方法this.getDataList()//1秒鐘备蚓,關(guān)閉下拉刷新setTimeout(()=>{wx.stopPullDownRefresh()},1000);}
4. 上拉觸底
onReachBottom:function(){//當(dāng)前頁(yè)碼加1this.data.pageIndex++//重新調(diào)用加載數(shù)據(jù)的方法this.getDataList()}
5. 添加頁(yè)面
<viewclass="content"><viewclass="item flex"><label>題目:</label><!-- 通過(guò)model:value的方式,將表單里面的數(shù)據(jù)跟js里面的數(shù)據(jù)進(jìn)行了雙向綁定囱稽,
? ? 雙向綁定指的是:一處被修改郊尝,另一處也一起修改--><inputclass="txt"placeholder="請(qǐng)輸入題目"model:value="{{title}}"/></view><viewclass="item flex"><label>答案:</label><textareaclass="txt"placeholder="請(qǐng)輸入答案"style="height:100rpx"model:value="{{answer}}"></textarea></view><viewclass="item flex"><label>分類:</label><inputdisabledbindtap="gotoTypeList"class="txt"placeholder="請(qǐng)選擇分類"model:value="{{section_name}}"/></view><viewclass="item flex"><label>解析:</label><textareaclass="txt"placeholder="請(qǐng)輸入解析"style="height:100rpx"model:value="{{desc}}"></textarea></view><viewclass="item flex"><buttonbindtap="click">添加</button></view></view>
6. 添加方法
//添加按鈕點(diǎn)擊事件asyncclick(){//非空驗(yàn)證if(!this.data.title||!this.data.section_id||!this.data.answer)returnwx.$msg('請(qǐng)輸入完整信息!')//請(qǐng)求后臺(tái)战惊,添加題目信息letres=awaitwx.$post('/Subject/AddSubject',{title:this.data.title,answer:this.data.answer,desc:this.data.desc,section_id:this.data.section_id})if(res){wx.$msg('添加成功流昏!')this.clear()//清空數(shù)據(jù)}}
7. 分類頁(yè)面
<viewclass="flex"><view><buttonbindtap="click"data-id="{{item.Id}}"data-name="{{item.Name}}"class="item"wx:for="{{typeList}}"wx:key="index">{{item.Name}}</button></view></view>
8. 獲取分類數(shù)據(jù)
//獲取分類信息的方法asyncgetTypeList(){lettypeList=awaitwx.$get('/Section/GetSections')this.setData({typeList})}
9. 返回分類數(shù)據(jù)
click(e){//獲取按鈕傳過(guò)的參數(shù)let{id,name}=wx.$key(e)//獲取當(dāng)前頁(yè)面棧。數(shù)組中第一個(gè)元素為首頁(yè)吞获,最后一個(gè)元素為當(dāng)前頁(yè)面况凉。letpages=getCurrentPages()//獲取上一個(gè)頁(yè)面letprev_page=pages[pages.length-2]//設(shè)置上一個(gè)頁(yè)面中的分類id和分類名稱prev_page.setData({section_id:id,section_name:name})//返回前一個(gè)頁(yè)面wx.navigateBack()}
10. 獲取url參數(shù)
onLoad:function(options){if(Object.keys(options).length>0){let{id,name}=optionsthis.setData({section_id:id,section_name:name})}}
11. 顯示詳情
<viewclass="content"><viewclass="title">{{data.Title}}</view><viewclass="hr">答案:</view><viewclass="answer">{{data.Answer}}</view><viewclass="hr">解析:</view><viewclass="desc">{{data.Desc}}</view></view>
onLoad:function(options){if(Object.keys(options).length>0){this.data.id=options.id}//調(diào)用獲取數(shù)據(jù)的方法this.getData()},//獲取數(shù)據(jù)的方法asyncgetData(){//根據(jù)題目的id,獲取題目信息letdata=awaitwx.$get('/Subject/GetSubject',{id:this.data.id})this.setData({data})}
五各拷、Vant組件庫(kù)
1. 下載Vant Weapp
步驟一:通過(guò) npm 安裝
npm i @vant/weapp -S --production
步驟二:修改 app.json
將 app.json 中的 "style": "v2" 去除刁绒,小程序的新版基礎(chǔ)組件強(qiáng)行加上了許多樣式,難以覆蓋撤逢,不關(guān)閉將造成部分組件樣式混亂膛锭。
步驟三:修改 project.config.json
開(kāi)發(fā)者工具創(chuàng)建的項(xiàng)目,miniprogramRoot 默認(rèn)為 miniprogram蚊荣,package.json 在其外部初狰,npm 構(gòu)建無(wú)法正常工作。
需要手動(dòng)在 project.config.json 內(nèi)添加如下配置互例,使開(kāi)發(fā)者工具可以正確索引到 npm 依賴的位置奢入。
"setting":{..."packNpmManually":true,"packNpmRelationList":[{"packageJsonPath":"./package.json","miniprogramNpmDistDir":"./miniprogram/"}]}
注意: 由于目前新版開(kāi)發(fā)者工具創(chuàng)建的小程序目錄文件結(jié)構(gòu)問(wèn)題,npm構(gòu)建的文件目錄為miniprogram_npm媳叨,并且開(kāi)發(fā)工具會(huì)默認(rèn)在當(dāng)前目錄下創(chuàng)建miniprogram_npm的文件名腥光,所以新版本的miniprogramNpmDistDir配置為'./'即可。
步驟四:構(gòu)建 npm 包
點(diǎn)擊工具-->構(gòu)建npm
并勾選本地設(shè)置-->使用npm模塊選項(xiàng)
在.json文件中配置使用的組件糊秆,可以在全局中配置武福,也可以在單獨(dú)頁(yè)面中配置。
"usingComponents":{"van-field":"@vant/weapp/field/index","van-picker":"@vant/weapp/picker/index","van-popup":"@vant/weapp/popup/index","van-button":"@vant/weapp/button/index","van-divider":"@vant/weapp/divider/index","van-empty":"@vant/weapp/empty/index","van-search":"@vant/weapp/search/index"}
2. 列表頁(yè)添加搜索功能
<!-- 導(dǎo)入wxs文件 --><wxssrc="../../wxs/filter.wxs"module="filter"/><viewclass="container"><van-searchmodel:value="{{ title }}"placeholder="請(qǐng)輸入搜索關(guān)鍵詞"bind:search="onSearch"bind:clear="onClear"/><navigatorurl="../vantdetails/vantdetails?id={{item.Id}}"class="data"wx:for="{{dataList}}"wx:key="index"><viewclass="title">{{item.Title}}</view><viewclass="flex j-s a-c desc"><view>{{item.Section.Name}}</view><view>{{filter.formatTime(item.Createtime)}}</view></view></navigator></view><viewbindtap="click"class="btn_add">+</view>
//搜索框的搜索方法onSearch(){this.data.pageIndex=1//頁(yè)碼重新設(shè)置為1this.getDataList()//調(diào)用獲取數(shù)據(jù)的方法},//搜索框的清空方法onClear(){//清空titlethis.setData({title:''})this.data.pageIndex=1//頁(yè)碼重新設(shè)置為1this.getDataList()//調(diào)用獲取數(shù)據(jù)的方法}
3. 重構(gòu)添加頁(yè)面
<viewclass="content"><viewclass="item"><van-fieldlabel="題目"title-width="80rpx"model:value="{{ title }}"placeholder="請(qǐng)輸入題目"required/></view><viewclass="item"><van-fieldlabel="答案"title-width="80rpx"type="textarea"autosizecustom-style="height:150rpx"model:value="{{ answer }}"placeholder="請(qǐng)輸入答案"required/></view><viewclass="item"><van-fieldlabel="分類"title-width="80rpx"readonlymodel:value="{{ section_name }}"placeholder="請(qǐng)選擇分類"bindtap="showPopup"required/></view><viewclass="item"><van-fieldlabel="解析"title-width="80rpx"type="textarea"autosizecustom-style="height:150rpx"model:value="{{ desc }}"placeholder="請(qǐng)輸入答案"/></view><viewclass="item flex j-c"><van-buttonloading="{{loading}}"loading-text="添加中..."type="primary"blockroundicon="plus"bindtap="click">添加題目</van-button></view></view><van-popupposition="bottom"show="{{ show }}"bind:close="onClose"><van-pickershow-toolbartitle="請(qǐng)選擇分類"value-key="Name"columns="{{ typeList }}"bind:cancel="onClose"bind:confirm="onConfirm"/></van-popup>
//獲取分類信息的方法asyncgetTypeList(){lettypeList=awaitwx.$get('/Section/GetSections')this.setData({typeList})},//顯示彈出層方法showPopup(){this.setData({show:true});},//關(guān)閉彈出層方法onClose(){this.setData({show:false});},//選擇器確定方法onConfirm(event){const{value}=event.detail;//設(shè)置分類編號(hào)和分類名稱this.setData({section_id:value.Id,section_name:value.Name,show:false})},//添加按鈕點(diǎn)擊事件asyncclick(){//非空驗(yàn)證if(!this.data.title||!this.data.section_id||!this.data.answer)returnwx.$msg('請(qǐng)輸入完整信息痘番!')//請(qǐng)求后臺(tái)捉片,添加題目信息this.setData({loading:true})letres=awaitwx.$post('/Subject/AddSubject',{title:this.data.title,answer:this.data.answer,desc:this.data.desc,section_id:this.data.section_id})if(res){wx.$msg('添加成功!')this.setData({loading:false})this.clear()//清空數(shù)據(jù)}},//清空方法clear(){this.setData({title:'',answer:'',desc:'',section_id:0,section_name:''})}
4. 重構(gòu)詳情頁(yè)
<viewclass="content"wx:if="{{data}}"><viewclass="title">{{data.Title}}</view><van-dividerfontSize="15"contentPosition="left"textColor="#248067"borderColor="#248067">答案</van-divider><viewclass="answer">{{data.Answer}}</view><van-dividerfontSize="15"contentPosition="left"textColor="#248067"borderColor="#248067">解析</van-divider><viewclass="desc">{{data.Desc}}</view></view><van-emptywx:elsedescription="暫無(wú)數(shù)據(jù)"/>
onLoad:function(options){if(Object.keys(options).length>0){this.data.id=options.id}//調(diào)用獲取數(shù)據(jù)的方法this.getData()},//獲取數(shù)據(jù)的方法asyncgetData(){//根據(jù)題目的id汞舱,獲取題目信息letdata=awaitwx.$get('/Subject/GetSubject',{id:this.data.id})this.setData({data})},onPullDownRefresh:function(){//重新獲取詳情信息//調(diào)用獲取數(shù)據(jù)的方法this.getData()//1秒后關(guān)閉下拉刷新setTimeout(()=>{wx.stopPullDownRefresh()},1000);}
六伍纫、自定義組件1
1. tabMenu組件
<viewclass="flex item">
<viewclass="title">{{label}}</view><viewdata-active="{{index}}"bindtap="change"class="tab {{active===index?'active':''}}"wx:key="index"wx:for="{{list}}">{{item}}</view>
</view>
/* 注意:組件中默認(rèn)不會(huì)引入全局樣式,如果要用全局樣式昂芜,需要手動(dòng)引入 */@import'../../app.wxss';.item{margin:10rpx0;}.title{padding:10rpx20rpx;color:#248067;}.tab{padding:10rpx20rpx;border:1pxsolid#eeeeee;margin:02px;}.tab.active{background:#248067;color:#ffffff;}
/**
? * 組件的屬性列表:用于接收調(diào)用組件的頁(yè)面?zhèn)鬟^(guò)來(lái)的數(shù)據(jù)
? */properties:{//添加組件的屬性//該屬性接收需要呈現(xiàn)的數(shù)據(jù)list:{//類型是數(shù)組莹规,表示只能給該屬性傳數(shù)組值type:Array},//該屬性接收高亮索引active:{//該屬性是數(shù)字類型type:Number,//該屬性的默認(rèn)值0value:0},//該屬性接收標(biāo)題信息label:{type:String,value:'選項(xiàng)'}},/**
? * 組件的方法列表:組件的方法,必須要放在這里定義
? */methods:{change(e){let{active}=wx.$key(e)this.setData({active})
//組件內(nèi)部觸發(fā)一個(gè)事件//組件外部通過(guò)執(zhí)行該事件泌神,通過(guò)事件方法良漱,獲取傳出來(lái)的數(shù)據(jù)// this.triggerEvent("change",{active,label:this.data.label})this.triggerEvent("change",active)},}
2. counter組件
<viewclass="flex a-c item"><viewclass="title">{{label}}</view><viewclass="jian"bindtap="jian">-</view><viewclass="count">{{count}}</view><viewclass="jia"bindtap="jia">+</view></view>
@import'../../app.wxss';.item{margin:10rpx0;}.title{padding:5rpx10rpx;}.jian,.jia{width:50rpx;height:50rpx;text-align:center;line-height:50rpx;border:1pxsolid#eeeeee;background:#248067;color:#ffffff;}.count{width:50rpx;height:50rpx;text-align:center;padding:010rpx;}
/**
? * 組件的屬性列表
? */properties:{//標(biāo)題label:{type:String},//初始值count:{type:Number,value:1},//最小值min:{type:Number,value:1},//最大值max:{type:Number,value:99999}},
/**
? * 組件的方法列表
? */methods:{//減方法jian(){letcount=this.data.count-1if(count<this.data.min){count=this.data.minwx.$msg('不能更少了',1000,'none')}this.setData({count})//觸發(fā)事件this.triggerEvent('change',count)},//加方法jia(){letcount=this.data.count+1if(count>this.data.max){count=this.data.maxwx.$msg('不能更多了',1000,'none')}this.setData({count})//觸發(fā)事件this.triggerEvent('change',count)}}
3. 頁(yè)面中使用
"usingComponents":{"tabMenu":"../../components/tabMenu/tabMenu","counter":"../../components/counter/counter"},
<viewclass="content">{{wd}}-{{tf}}-{{pl}}<tabMenudata-key="wd"label="溫度"list="{{wdList}}"active="{{wd}}"bind:change="syncData"></tabMenu><tabMenudata-key="tf"label="糖分"list="{{tfList}}"active="{{tf}}"bind:change="syncData"></tabMenu><tabMenudata-key="pl"label="配料"list="{{plList}}"active="{{pl}}"bind:change="syncData"></tabMenu><viewclass="line"></view>{{yfcount}}-{{kzcount}}-{{xzcount}}<counterdata-key="yfcount"label="衣服:"count="{{yfcount}}"min="{{1}}"max="{{10}}"bind:change="syncData"></counter><counterdata-key="kzcount"label="褲子:"count="{{kzcount}}"min="{{3}}"max="{{12}}"bind:change="syncData"></counter><counterdata-key="xzcount"label="鞋子:"count="{{xzcount}}"min="{{0}}"max="{{8}}"bind:change="syncData"></counter></view>
//切換高亮syncData(e){let{key}=wx.$key(e)this.setData({[key]:e.detail})},/**
? * 頁(yè)面的初始數(shù)據(jù)
? */data:{wdList:['常溫','去冰','少冰','熱飲'],wd:0,tfList:['全糖','半糖','少糖','無(wú)糖'],tf:0,plList:['珍珠','椰果','布丁','紅豆'],pl:0,yfcount:2,kzcount:3,xzcount:5},