小程序promise解决地狱回调及封装请求

1.promise解决地狱回调:

vscode中:

小程序中:

// pages/promise/promise.js

Page({

    /**

     * 页面的初始数据

     */

    data: {

    },

    /**

     * 生命周期函数--监听页面加载

     */

    onLoad: function (options) {

        this.promiseFn()

            .then(data => {

                /*  console.log(data); */

                return data;

            })

            .then(data2 => {

                console.log(data2);

                return data2

            })

            /* 使用catch来接收错误信息 */

            .catch(err => {

                console.log(err);

            })

            .then(data3 => {

                console.log(data3);

                return data3

            })

    },

    promiseFn: function () {

        /* 使用promise封装请求 */

        /* 返回一个promise实例化对象 */

        return new Promise((resolve, reject) => {

            wx.request({

                url: 'url',

                success: (res) => {

                    resolve(res.data)

                },

                fail: (err) => {

                    reject(err)

                }

            })

        })

    },

    /**

     * 生命周期函数--监听页面初次渲染完成

     */

    onReady: function () {

    },

    /**

     * 生命周期函数--监听页面显示

     */

    onShow: function () {

    },

    /**

     * 生命周期函数--监听页面隐藏

     */

    onHide: function () {

    },

    /**

     * 生命周期函数--监听页面卸载

     */

    onUnload: function () {

    },

    /**

     * 页面相关事件处理函数--监听用户下拉动作

     */

    onPullDownRefresh: function () {

    },

    /**

     * 页面上拉触底事件的处理函数

     */

    onReachBottom: function () {

    },

    /**

     * 用户点击右上角分享

     */

    onShareAppMessage: function () {

    }

})

2.封装请求的方法:


简易登录页项目练习:

登录页内容:

wxml部分:

<view class="main">

<view class="title">欢迎来到我的书城</view>

    <van-cell-group>

    <van-field model:value="{{ email }}"

     required clearable label="邮箱"

      icon="question-o"

       placeholder="请输入邮箱" 

       bind:change="emailChange" 

       error-message="{{errEmail}}" />

    <van-field model:value="{{ pwd }}"

     type="password" 

     label="密码" 

     placeholder="请输入密码" 

     required border="{{ false }}" 

     bind:change="pwdChange" 

     error-message="{{errpassword}}" />

</van-cell-group>

</view>

<view class="btn-sty">

    <van-button round type="primary" bindtap="login">登录</van-button>

    <van-button round type="info" class="register">注册</van-button>

</view>

wxss部分:

/* pages/denglu/denglu.wxss */

.btn-sty{

  margin: 20px;

  text-align: center;

}

.register{

    margin-left: 20px;

}

.main{

    margin-top: 10px;

}

.title{

    text-align: center;

    padding: 20px;

    padding-top: 0px;

    font-size: 30px;

    color: #1989FA;

}

js部分:

// pages/denglu/denglu.js

const {loginHttp} = require('../../http/api')

Page({

    /**

     * 页面的初始数据

     */

    data: {

        email:'',

        pwd:'',

        errEmail:'',

        errpassword:''

     },

    login:function(){

    if(this.data.email==''){

        this.setData({

            errEmail:'邮箱不能为空'

        })

       return

    }

    if(this.data.pwd==''){

        this.setData({

            errpassword:'密码不能为空'

        })

        return

    }


    loginHttp('/api/auth/login',{email:this.data.email,password:this.data.pwd},'POST')

    .then(res=>{

        console.log(res);

        console.log('正常渲染画面');

        let {access_token} = res;

        wx.setStorageSync('token', access_token)

        wx.switchTab({

          url: '/pages/home/home',

        })

    })

    .catch(err=>{

        console.log(err);

        console.log('页面被外星人抓走了');

    })

    },

    /* emailChange:function(e){

      this.setData({

          email:e.detail

      })

    },

    pwdChange:function(e){

      this.setData({

        pwd:e.detail

      })

    }, */

    onChange(event) {

        // event.detail 为当前输入的值

        console.log(event.detail);

      },

    /**

     * 生命周期函数--监听页面加载

     */

    onLoad: function (options) {

        loginHttp('/api/auth/login',{email:'test@a.com',password:'123123'},'POST')

    .then(res=>{

        console.log(res);

    })

    .catch(err=>{

        console.log(err);

        console.log('页面被外星人抓走了');

    })

    },

    /**

     * 生命周期函数--监听页面初次渲染完成

     */

    onReady: function () {

    },

    /**

     * 生命周期函数--监听页面显示

     */

    onShow: function () {

    },

    /**

     * 生命周期函数--监听页面隐藏

     */

    onHide: function () {

    },

    /**

     * 生命周期函数--监听页面卸载

     */

    onUnload: function () {

    },

    /**

     * 页面相关事件处理函数--监听用户下拉动作

     */

    onPullDownRefresh: function () {

    },

    /**

     * 页面上拉触底事件的处理函数

     */

    onReachBottom: function () {

    },

    /**

     * 用户点击右上角分享

     */

    onShareAppMessage: function () {

    }

})

json部分:

{

  "navigationBarTitleText": "登录页面",

  "usingComponents": {

    "van-cell": "@vant/weapp/cell/index",

    "van-cell-group": "@vant/weapp/cell-group/index",

    "van-field": "@vant/weapp/field/index",

    "van-button": "@vant/weapp/button/index"

  }

}

效果图:


首页内容:

wxml部分:

<MySwiper slides="{{slides}}"/>

<ListItem itemList="{{itemList}}"></ListItem>

JSON部分:

{

  "usingComponents": {

    "MySwiper":"/components/MySwiper/MySwiper",

    "ListItem":"/components/ListItem/ListItem"

  },

  "navigationBarTitleText": "首页"

}

JS部分:

// pages/home/home.js

const {indexHttp} = require('../../http/api')

Page({

    /**

     * 页面的初始数据

     */

    data: {

        slides:{},

        itemList:[]

    },


    /**

     * 生命周期函数--监听页面加载

     */

    onLoad: function (options) {

        indexHttp('/api/index',{},'GET')

        .then(res=>{

            let {slides,goods:{data}} = res;

            this.setData({slides,itemList:data})

            console.log(res);

        })

        .catch(err=>{

            console.log(err);

        })

    },

    /**

     * 生命周期函数--监听页面初次渲染完成

     */

    onReady: function () {

    },

    /**

     * 生命周期函数--监听页面显示

     */

    onShow: function () {

    },

    /**

     * 生命周期函数--监听页面隐藏

     */

    onHide: function () {

    },

    /**

     * 生命周期函数--监听页面卸载

     */

    onUnload: function () {

    },

    /**

     * 页面相关事件处理函数--监听用户下拉动作

     */

    onPullDownRefresh: function () {

    },

    /**

     * 页面上拉触底事件的处理函数

     */

    onReachBottom: function () {

    },

    /**

     * 用户点击右上角分享

     */

    onShareAppMessage: function () {

    }

})

组件MySwiper:

wxml部分:

<!--components/MySwiper/MySwiper.wxml-->

<swiper indicator-dots="{{indicatorDots}}" 

autoplay="{{autoplay}}" 

interval="{{interval}}" 

duration="{{duration}}" 

circular="{{circular}}">

    <block wx:for="{{slides}}" wx:key="*this">

        <swiper-item>

            <view class="swiper-item" bindtap="goTo" data-url="https://www.bilibili.com/video/BV1ub4y1x7FT?spm_id_from=333.337.search-card.all.click">

                <image src="{{item.img_url}}" class="img-sty"></image>

            </view>

        </swiper-item>

    </block>

</swiper>

wxss部分:

/* components/MySwiper/MySwiper.wxss */

swiper,.img-sty{

    width: 100%;

    height: 180px;

}

JS部分:

// components/MySwiper/MySwiper.js

Component({

    /**

     * 组件的属性列表

     */

    properties: {

        slides:{

            type:Array,

            value:[{img_url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091213%2Fnxbrhvkcwp2nxbrhvkcwp2.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648601547&t=70234d4610ef4197e14ee30741978e97'}, {img_url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091010%2F1pqhjsj1pdh1pqhjsj1pdh.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648601547&t=9dccfb1177457d4f7fd353d98585935d'}, {img_url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091023%2Fhrhi1fi1vhbhrhi1fi1vhb.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648601547&t=e3e4ade551143711f2ce593b96e0cb30'}]

        }

    },

    /**

     * 组件的初始数据

     */

    data: {

        indicatorDots: true,

        vertical: false,

        autoplay: true,

        interval: 2000,

        duration:500,

        circular:true,

    },

    /**

     * 组件的方法列表

     */

    methods: {

        goTo(e){

            let {currentTarget:{dataset:{url}}} = e;

            wx.navigateTo({

              url: '/pages/web/web?url='+url,

            })

        }

    }

})

组件ListItem:

wxml部分:

<!--components/ListItem/ListItem.wxml-->

<block wx:for="{{itemList}}" wx:key="index">

    <view class="flex item" bindtap="go" data-url="{{item.cover_url}}">

    <image class="img1" src="{{item.cover_url}}"></image>

    <view class="row">

        <view class="title">

            {{item.title}}

        </view>

        <view class="dec van-multi-ellipsis--l2">

            {{item.description}}

        </view>

    </view>

</view>

</block>

wxss部分:

/* components/ListItem/ListItem.wxss */

@import '/miniprogram_npm/@vant/weapp/common/index.wxss';

.flex{

    display: flex;

  }

.item{

    padding:5px;

}

.img1{

    width: 120px;

    height: 120px;

    display: block;

    border-radius: 5px;

}

.row{

    flex:1;

    height: 120px

}

.title{

    padding:10px;

    text-overflow:ellipsis;

    display: -webkit-box;

    -webkit-line-clamp: 1;

    word-break: break-all;

    -webkit-box-orient: vertical;

    height: 14px;

    overflow: hidden;

}

.dec{

    padding: 0 10px;

}

JS部分:

// components/ListItem/ListItem.js

Component({

    /**

     * 组件的属性列表

     */

    properties: {

        itemList:{

            type:Array,

            value:{}

        }

        /* rItem:{

            type:Object,

            value:{

                url:'https://www.enterdesk.com/face/96790.html',

                imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_360_360%2F80%2F4b%2Fb5%2F804bb51279b3f24270e275e0b8cc9395.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1648446790&t=402c74db5512e66fcbbf8a0493275401",

                title:"皮卡丘",

                content:"十万伏特十万伏特十万伏特十万伏特十万伏特十万伏特十万伏特十万伏特十万伏特"

            }

        } */

    },

    /**

     * 组件的初始数据

     */

    data: {

    },

    /**

     * 组件的方法列表

     */

    methods: {

        go(e){

            let url = e.currentTarget.dataset.url;

            wx.navigateTo({

              url: '/pages/web/web?url='+url,

            })

        }

    }

})

app.JSON配置tabBar部分:

{

    "pages": [

        "pages/denglu/denglu",

        "pages/home/home",

        "pages/promise/promise",

        "pages/index/index",

        "pages/logs/logs",

        "pages/web/web"

    ],

    "window": {

        "backgroundTextStyle": "light",

        "navigationBarBackgroundColor": "#fff",

        "navigationBarTitleText": "Weixin",

        "navigationBarTextStyle": "black"

    },

    "tabBar": {

        "color": "#000",

        "selectedColor": "#fff",

        "backgroundColor": "#ccc",

        "list": [

            {

                "pagePath": "pages/home/home",

                "text": "首页",

                "iconPath": "/img/1.png",

                "selectedIconPath": "/img/4.png"

            },

            {

                "pagePath": "pages/logs/logs",

                "text": "日志",

                "iconPath": "/img/3.png",

                "selectedIconPath": "/img/4.png"

            }

        ]

    },

    "usingComponents": {

        "van-button": "@vant/weapp/button/index"

    },

    "sitemapLocation": "sitemap.json"

}

跳转的web部分:

wxml部分:

<web-view src="{{url}}"></web-view>

JS部分:

// pages/web/web.js

Page({

    /**

     * 页面的初始数据

     */

    data: {

     url:''

    },

    /**

     * 生命周期函数--监听页面加载

     */

    onLoad: function (options) {

    this.setData({

        url:options.url

    })

    },

    /**

     * 生命周期函数--监听页面初次渲染完成

     */

    onReady: function () {

    },

    /**

     * 生命周期函数--监听页面显示

     */

    onShow: function () {

    },

    /**

     * 生命周期函数--监听页面隐藏

     */

    onHide: function () {

    },

    /**

     * 生命周期函数--监听页面卸载

     */

    onUnload: function () {

    },

    /**

     * 页面相关事件处理函数--监听用户下拉动作

     */

    onPullDownRefresh: function () {

    },

    /**

     * 页面上拉触底事件的处理函数

     */

    onReachBottom: function () {

    },

    /**

     * 用户点击右上角分享

     */

    onShareAppMessage: function () {

    }

})

效果图:


详情可参考:

vant组件:https://youzan.github.io/vant-weapp/#/button

微信小程序官方教学:https://developers.weixin.qq.com/miniprogram/dev/component/


张sir手摸手详细教学:https://www.bilibili.com/video/BV1ub4y1x7FT?spm_id_from=333.337.search-card.all.click




©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容