微信小程序 常用操作

小程序登录

login: function () {
   wx.login({
       success: loginRes => {
           console.log(loginRes);
           if (loginRes.code) {
           	   // 返回值
               // encryptedData:XXXX"
               // errMsg: "getUserInfo:ok"
               // iv: "XXXX"
               // rawData: "{"nickName":"辉","gender":1,"language":"zh_CN","city":"","province":"Abu Dhabi","country":"United Arab Emirates","avatarUrl":"XXXX"}"
               // signature: "XXXX"
               wx.getUserInfo({
                   withCredentials: true,
                   success: res => {
                       console.log(res);
                       wx.setStorageSync('hasGetUserInfo', '1');
                       this.post({
                           url: 'wxapp/public/login',
                           data: {
                               code: loginRes.code,
                               encrypted_data: res.encryptedData,
                               iv: res.iv,
                               raw_data: res.rawData,
                               signature: res.signature
                           },
                           success: data => {
                               if (data.code == 1) {
                                   wx.showToast({
                                       title: '登录成功!',
                                       icon: 'success',
                                       duration: 1000
                                   });

                                   try {
                                       wx.setStorageSync('login', '1');
                                       wx.setStorageSync('token', data.data.token);
                                       wx.setStorageSync('user', data.data.user);
                                   } catch (e) {
                                   }

                                   setTimeout(function () {
                                       wx.switchTab({
                                           url: '/pages/index/index',
                                           success: res => {
                                               getCurrentPages()[0].onPullDownRefresh()
                                           }
                                       });
                                   }, 1000);
                               }

                           },
                           complete: () => {
                               tryingLogin = false;
                           }
                       });
                   },
                   fail: (res) => {
                       console.log(res);
                       tryingLogin = false;
                       if (res.errMsg == "getUserInfo:cancel" || res.errMsg == "getUserInfo:fail auth deny") {
                           wx.showModal({
                               title: '用户授权失败',
                               showCancel: false,
                               content: '请删除此小程序重新授权!',
                               success: function (res) {
                                   if (res.confirm) {
                                       console.log('用户点击确定')
                                   }
                               }
                           });
                       }
                   }
               });
           } else {
               tryingLogin = false;
           }
       },
       fail: () => {
           tryingLogin = false;
       }
   });
},

HTTP请求封装

var host = "xxxxx";
var tryingLogin = false;
module.exports = {
    HOST: host,
    API_ROOT: host + '/api/',
    API_VERSION: '1.1.0',
    post(options) {
        this.request(options);
    },
    get(options) {
        options.method = 'GET';
        this.request(options);
    },
    delete(options) {
        options.method = 'DELETE';
        this.request(options);
    },
    put(options) {
        options.method = 'PUT';
        this.request(options);
    },
    request(options) {
        var apiRoot = this.API_ROOT;
        var token   = '';
        try {
            token = wx.getStorageSync('token')
        } catch (e) {
            // Do something when catch error
        }

        var requireLogin = true;

        if (typeof options.login == 'undefined' || options.login == true) {
            requireLogin = true;
        } else {
            requireLogin = false;
        }

        wx.request({
            url: apiRoot + options.url,
            data: options.data,
            method: options.method ? options.method : 'POST',
            header: {
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/x-www-form-urlencoded',
                'XX-Token': token,
                'XX-Device-Type': 'wxapp',
                'XX-Api-Version': this.API_VERSION
            },
            success: res => {
                var data = res.data;
                if (data.code == 10001 && requireLogin) {

                    if (!tryingLogin) {
                        tryingLogin        = true;
                        var hasGetUserInfo = wx.getStorageSync('hasGetUserInfo');
                        if (hasGetUserInfo) {
                            wx.showToast({
                                title: '正在重新登录',
                                icon: 'success',
                                duration: 1000
                            });
                            setTimeout(() => {
                                this.login();
                            }, 1000);
                        } else {
                            this.login();
                        }

                    }
                    // 登录注册
                    let currentPages = getCurrentPages();

                    console.log('-------no login!---------');

                    let currentRoute = currentPages.pop()['__route__'];
                    if (currentRoute != 'pages/login/login') {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        });
                    }

                } else {
                    options.success(data);
                }

            },
            fail: function (res) {
                if (options.fail) {
                    options.fail(res)
                }
            },
            complete: options.complete ? options.complete : null
        });
    }
}

下拉刷新

onPullDownRefresh() {
    this.currentPageNumber = 1;
    this.setData({
        noMoreData: false,
        noData: false
    });
    api.get({
        url: 'portal/articles',
        data: {
            order:'-published_time'
        },
        success: data => {
            let newItems = api.updatePageList('id', data.data.list, this.formatListItem, true);
            console.log(newItems);
            this.setData({
                list: newItems
            });

            if (data.data.list.length > 0) {
                this.currentPageNumber++;
            } else {
                this.setData({
                    noMoreData: true
                });

                // 没有数据
                // this.setData({
                //     noMoreData: true,
                //     noData: true
                // });
            }

            wx.stopPullDownRefresh();
        }
    });
},

上拉加载

pullUpLoad() {
    if (this.data.loadingMore || this.data.noMoreData) return;
    this.setData({
        loadingMore: true
    });
    wx.showNavigationBarLoading();

    api.get({
        url: 'portal/articles',
        data: {
            page: this.currentPageNumber,
            order:'-published_time'
        },
        success: data => {
            let newItems = api.updatePageList('id', data.data.list, this.formatListItem);
            console.log(newItems);
            this.setData({
                list: newItems
            });
            if (data.data.list.length > 0) {
                this.currentPageNumber++;
            } else {
                this.setData({
                    noMoreData: true
                });

                // 没有数据
                // this.setData({
                //     noMoreData: true,
                //     noData: true
                // });
            }
        },
        complete: () => {
            this.setData({
                loadingMore: false
            });
            wx.hideNavigationBarLoading();
        }
    });
},

文件上传

uploadFile(options) {
    options.url = this.API_ROOT + options.url;
    let token = this.getToken();
    let that = this;
    let oldSuccess  = options.success;
    options.success = function (res) {
        console.log(res.data);
        let data = JSON.parse(res.data);
        console.log(data);
        if (data.code == 0 && data.data && data.data.code && data.data.code == 10001) {
            that.login();
        } else {
            oldSuccess(data);
        }
    }
    options.header = {
        'Content-Type': 'multipart/form-data',
        'XX-Token': token,
        'XX-Device-Type': 'wxapp',
        'XX-Api-Version': this.API_VERSION
    };
    wx.uploadFile(options);
},

图片预览

wx.previewImage({
  current: nowImgUrl, // 当前显示图片的http链接
  urls: that.data[tagFrom].imageUrls // 需要预览的图片http链接列表
})

返回上个页面

wx.navigateBack({
     delta: 1
 });

存储

wx.setStorageSync('hasGetUserInfo', '1'); 存入
wx.getStorageSync('hasGetUserInfo');  取出

Loading等待

wx.showLoading({
      title: '加载中',
})
setTimeout(function(){
      wx.hideLoading()
},2000)

提示框

wx.showToast({
	title: '登录成功!',
	icon: 'success',
	duration: 1000
});

确认框

wx.showModal({
    title: '用户授权失败',
    showCancel: false,
    content: '请删除此小程序重新授权!',
    success: function (res) {
        if (res.confirm) {
            console.log('用户点击确定')
        }
    }
});

底部弹出列表框

wx.showActionSheet({
   itemList: ['列1','列2','列3'],//显示的列表项
   success: function (res) {//res.tapIndex点击的列表项
      console.log("点击了列表项:" + that[res.tapIndex])
   },
   fail: function (res) { },
   complete:function(res){ }
})

跳转 tabBar 页面

wx.switchTab({
	url: '/pages/index/index',
    success: res => {
        getCurrentPages()[0].onPullDownRefresh()
    }
});

跳转普通页面

wx.navigateTo({
     url: '/pages/login/login'
});

js页面模板

//index.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
 
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  
  // 其他函数事件(如点击等)
  onGetVerificationCode: function (e) {
  	console.log("eeee");
  },
})

小程序事件

<view bindtap="onGetVerificationCode">点击</view> //点击事件
<input name="Username" bindinput="onAccountInput" placeholder="手机号"/>  //监听输入框
<form bindsubmit="formSubmit"> //表单提交
<button  type="primary" formType="submit">提交</button> //设置表单类型
<image bindlongpress='longPress' src='{{userInfo.avatarUrl}}'></image>//长按事件

内置标签

<block wx:if="{{user.mobile}}"></block>//if判断
<block wx:for="{{list}}" wx:key="id">{{item}}</block>//for循环
<navigator url="/pages/favorite/index" ></navigator> //路由跳转
<include src="../../components/loading_more.wxml"/> //引入
<image  src="{{item.user.avatar}}" data-preview-url="{{item.more.thumbnail}}" mode="aspectFill"/> //图片组件

组件属性

hover-class//view、button、navigator可使用
catchtap//阻止冒泡的点击事件
发布了65 篇原创文章 · 获赞 20 · 访问量 2089

猜你喜欢

转载自blog.csdn.net/weixin_43993175/article/details/104110670