小程序原生项目搭建

1.打开微信开发者工具,选择新建项目,填写项目名称,选择目录,填写APPID,其他默认,点击新建。创建完成后,删除
默认页面,app.json页面下的pages里内容清空。
2.重构app.json文件

{
    "pages": [
        "pages/home/home",
        "pages/cates/cates",
        "pages/search/search",
        "pages/cart/cart",
        "pages/my/my",
        "pages/goods_detail/index",
        "pages/goods_list/index",
        "pages/confirm/index"
    ],
    "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#f44",
        "navigationBarTitleText": "黑马优购",
        "navigationBarTextStyle": "white"
    },
    "tabBar": {
        "selectedColor": "#f44",
        "list": [
            {
                "text": "首页",
                "pagePath": "pages/home/home",
                "iconPath": "/assets/icons/home.png",
                "selectedIconPath": "/assets/icons/home-active.png"
            },
            {
                "text": "分类",
                "pagePath": "pages/cates/cates",
                "iconPath": "/assets/icons/cates.png",
                "selectedIconPath": "/assets/icons/cates-active.png"
            },
            {
                "text": "搜索",
                "pagePath": "pages/search/search",
                "iconPath": "/assets/icons/search.png",
                "selectedIconPath": "/assets/icons/search-active.png"
            },
            {
                "text": "购物车",
                "pagePath": "pages/cart/cart",
                "iconPath": "/assets/icons/cart.png",
                "selectedIconPath": "/assets/icons/cart-active.png"
            },
            {
                "text": "我的",
                "pagePath": "pages/my/my",
                "iconPath": "/assets/icons/my.png",
                "selectedIconPath": "/assets/icons/my-active.png"
            }
        ]
    },
    "style": "v2",
    "usingComponents": {
        "stepper": "/components/stepper/index",
        "slide-delete": "/components/slide-delete/index"
    },
    "debug": true,
    "sitemapLocation": "sitemap.json"
}

3.重构App.js 封装Promise 使以后发起数据请求更加简单

App({
	globalData: {
		sysInfo: {}
	},

	async onLaunch() {
		this._promisifyWxApi()
	},
		_promisifyWxApi() {
		const that = this
		wx.requestAsync = function(params={}) {
			let {url, method, data, header, hideLoading} = params

			// 统一添加一个接口发起的渠道标识
			data = {
				...data,
				channel: 'miniapp'
			}

			// 统一过滤参数中值为undefined和null的参数
			const formatParams = {}

			for(let prop in data) {
				if (data[prop] !== undefined && data[prop] !== null) {
					formatParams[prop] = data[prop]
				}
			}

			if (!hideLoading) {
				wx.showLoading({
					title: '正在获取数据...'
				})
			}

			return new Promise((resolve, reject) => {
				wx.request({
            		url: 'https://uinav.com/api/public/v1/' + url,
                    // url: 'https://www.zhengzhicheng.cn/api/public/v1/' + url,
					method: method || 'GET',
					data: formatParams,
					header: {
						...header,
						'Authorization': that.globalData.token
					},
					success: res => {
						// 1. 网络正常
						if (res && +res.statusCode === 200) {
							// 业务逻辑正确
							if (res.data && res.data.meta) {
								if(+res.data.meta.status === 200) {
									resolve(res.data.message)
								}
								// 404
								else if (+res.data.meta.status == 404) {
									wx.showToast({
										title: '接口路径不存在',
										icon: 'none'
									})

									reject(res)
								}
								// 400 404 401 10000
								else {
									reject(res)
								}
							}
							else {
								reject(res)
							}
						}
						// 2. 网络不正常
						else {
							reject(res)
						}
					},
					fail: err => {
						reject(err)
					},
					complete: () => {
						if (!hideLoading) {
							wx.hideLoading()
						}
					}
				})
			})
		}
})

5.页面发起数据请求

const app = getApp()
 onLoad(options) {
        this._fetchData({
            path: 'home/swiperdata',
            type: 'swiperData'
        })
        this._fetchData({
            path: 'home/catitems',
            type: 'cates'
        })

        
 }
 async _fetchData(params={}) {
        const {path, type} = params

        try {
            let ret = await wx.requestAsync({
                url: path,
            })
            
            this.setData({
                [type]: ret
            })
        }
        catch(err) {
            console.log('catch err: ', err)
        }
    }
})

单一的数据接口

 onLoad(options) {
        this._fetchData()
    },
    async _fetchData() {
        try {
            let cates = await wx.requestAsync({
                url: 'categories'
            })

            // 1. ReferenceError: 使用一个未定义的变量
            // 2. TypeError: 
            // throw new Error('aaa')

            this.setData({
                cates,
                winHeight: app.globalData.sysInfo.windowHeight
            })
        }
        catch(err) {
            console.log('err: ', err)
            this.setData({errMsg: '获取分类数据失败'})
        }
    },
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值