uniapp实现微信登录(前端部分,仅供参考~)

  1. html部分

    <template>
    	<view>
    		<button @click="wxLogin">微信授权登录button>
    		<u-popup :show="editInfoVisible" round="20">
    	      <view class="edit-modal">
    	        <view class="edit-title">编辑资料view>
    	        <view>
    	          <button open-type="chooseAvatar" @chooseavatar="chooseAvatar" class="avatar-btn">
    	            <u-avatar :src="avatarUrl" size="160rpx">u-avatar>
    	          button>
    	        view>
    	        <view>
    	          <input type="nickname" placeholder="请输入昵称" @change="setNickName" v-model="nickName" class="input-wrapper"/>
    	        view>
    	        <view>
    	          <button type="warn" @click="save">保存button>
    	        view>
    	      view>
    	    u-popup>
    	view>
    template>
    
  2. js部分

    import { saveUserInfo } from './api';
    export default {
    	data() {
    		return {
    			editInfoVisible: false,
    			avatarUrl: null,
    			nickName: null
    		}
    	},
    	computed: {
    		isFirstLogin() {
    			return uni.getStorageSync('nick_name') && uni.getStorageSync('avatar_url');
    		}
    	},
    	methods: {
    		wxLogin() {
    			uni.showModal({
    				title: '系统提示',
    				content: '确定微信授权登录吗?',
    				success: () => {
    					uni.showLoading({
    						title: '登录中...'
    					});
    					// 调用uni.login接口拿到code,去后台换取用户信息
    					uni.login({
    						provider: 'weixin',
    						success: (res) => {
    							this.getUserInfo(res.code);
    						}
    					})
    				}
    			});
    		},
    		getUserInfo(code) {
    			this.$store.dispatch('Login', code).then(res => {
    				uni.hideLoading();
    				if (this.isFirstLogin) {
    					this.showEditInfoPopup();
    				} else {
    					uni.reLaunch({
    	        			url: '/pages/index'
    	        		})
    				}
    			});
    		},
    		showEditInfoPopup() {
    			this.editInfoVisible = true;
    		},
    		hideEditInfoPopup() {
    			this.editInfoVisible = false;
    		},
    		chooseAvatar(e) {
    	        this.uploadFile(e.detail.avatarUrl);
            },
            uploadFile(src) {
            	uni.showLoading({
    	          title:'上传中...'
    	        });
    	        uni.uploadFile({
    	        	url: this.$BASE_URL + 'api/wxapi/upload',
    	        	fileType: 'image',
    	        	name: 'file',
    	        	filePath: src,
    	        	header: {
    	        		'Content-Type': 'multipart/form-data'
    	        	},
    	        	success: () => {
    	        		uni.hideLoading();
    	        		this.avatarUrl = this.$BASE_URL + JSON.parse(res.data).fileName?.slice(1);
    	        	}
    	        });
            },
            setNickName(e) {
            	this.nickName = e.detail.value;
            },
            save() {
            	if (!this.avatarUrl) {
            		uni.showToast({
            			title: '请上传头像',
            			icon: 'error'
            		})
            		return;
            	}
            	if (!this.nickName) {
            		uni.showToast({
            			title: '请输入昵称',
            			icon: 'error'
            		});
            		return;
            	}
            	this.hideEditInfoPopup();
            	this.setUserInfo();
            },
            setUserInfo() {
            	uni.showLoading({
            		title: '登录中...'
            	});
            	const params = {
            		openid: uni.getStorageSync('token'),
            		avatarUrl: this.avatarUrl,
            		nickName: this.nickName
            	};
            	this.$store.dispatch('ChangeUserInfo', params).then(res => {
            		uni.hideLoading();
            		uni.reLaunch({
            			url: '/pages/index'
            		})
            	});
            }
    	},
    }
    
  3. scss部分

    .edit-modal {
      padding: 30rpx;
    }
    .edit-title {
      font-weight: bold;
      font-size: 44rpx;
      line-height: 50rpx;
      margin-bottom: 50rpx;
    }
    .avatar-btn {
      width: 160rpx;
      height: 160rpx;
      padding: 0;
      border-radius: 50%;
      margin-bottom: 30rpx;
      .input-wrapper {
      font-size: 34rpx;
      margin-bottom: 50rpx;
    }
    }
    
  4. store部分

    import Vue from 'vue';
    import Vuex from 'vuex';
    import { goLogin, saveUserInfo } from './api';
    Vue.use(Vuex);
    export default new Vuex.Store({
    	state: {
    		token: uni.getStorageSync('token');
    		nickName: uni.getStorageSync('nick_name');
    		avatarUrl: uni.getStorageSync('avatar_url');
    	},
    	mutations: {
    		SET_TOKEN(state, token) {
    			state.token = token;
    			uni.setStorageSync('token', token);
    		},
    		SET_NICK_NAME(state, nickName) {
    			state.nickName = nickName;
    			uni.setStorageSync('nick_name', nickName);
    		},
    		SET_AVATAR_URL(state, avatarUrl) {
    			state.avatarUrl = avatarUrl;
    			uni.setStorageSync('avatar_url', avatarUrl);
    		},
    	},
    	actions: {
    		Login({commit}, code) {
    			return new Promise((resolve, reject) => {
    				goLogin({code}).then(res => {
    					commit('SET_TOKEN', res.data.openid);
    					commit('SET_NICK_NAME', res.data.nickName);
    					commit('SET_AVATAR_URL', res.data.avatarUrl);
    					resolve();
    				}).catch(error => {
    					reject(error);
    				});
    			});
    		},
    		ChangeUserInfo({commit}, params) {
    			return new Promise((resolve, reject) => {
    				saveUserInfo(params).then(res => {
    					commit('SET_NICK_NAME', res.data.nickName);
    					commit('SET_AVATAR_URL', res.data.avatarUrl);
    					resolve();
    				}).catch(error => {
    					reject(error);
    				});
    			});
    		}
    	}
    });
    
  5. api部分

    import request from '@/utils/request'; // 封装的request
    export function goLogin(data) {
    	return request({
    		method: 'post',
    		url: 'api/wxapi/wxlogin',
    		headers: {
    			isToken: false
    		},
    		data
    	})
    }
    export function saveUserInfo(data) {
    	return request({
    		method: 'post',
    		url: 'api/wxapi/saveUserInfo',
    		data
    	});
    }
    

你可能感兴趣的:(uniapp,uni-app,微信,前端)