【微信小程序+node】微信小程序使用自定义组件和注意事项-05

自定义一个用户登录的,弹出框的组件做例子

【微信小程序+node】微信小程序使用自定义组件和注意事项-05
【微信小程序+node】微信小程序使用自定义组件和注意事项-05

创建一个子级弹出框组件

js

import Util from '../../utils/util.js';
import {baseInfo} from "../../utils/config";
import {setRoleId, setSessionKey, setToken, setUserId, setUserInfo} from "../../utils/storage";

let app = getApp();

//特别注意这里不是page而是Component
Component({
	//子级接收父级传过来的值,名称变量需要跟父级传过来的值保持一致
  properties: {
    isHidden: {
      type: Boolean,
      value: true,
    },
    //是否自动登录
    isAuto: {
      type: Boolean,
      value: true,
    },
    isGoIndex:{
      type: Boolean,
      value:true,
    },
  },
  data: {
    cloneIner: null,
    loading:false,
    errorSum:0,
    errorNum:3,
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false
  },
  attached() {
    //判断微信是否可以使用wx.getUserProfile
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  //组件的函数需要使用methods包住
  methods: {
    getUserProfile(e) {
      wx.showLoading()
      wx.getUserProfile({
        desc: '用于完善会员资料',
        success: (userInfoData) => {
          Util.getCodeLogin((res)=>{
            this.getWxUserInfo(userInfoData,res);
          })
        }
      })
    },
    getUserInfo(e) {
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
    },
    close(){
      let pages = getCurrentPages();
      let currPage  = pages[pages.length - 1];
      if(this.data.isGoIndex){
        wx.switchTab({url:'/pages/index/index'});
      }else{
        this.setData({
          isHidden: true
        });
        if (currPage && currPage.data.isHidden != undefined){
          currPage.setData({ isHidden:true});
        }
      }
    },
    getWxUserInfo(userInfoData,res){
      let that = this;
      let code = res.code;
      let nickName = userInfoData.userInfo.nickName;
      let avatarUrl = userInfoData.userInfo.avatarUrl;
      //发起网络请求
      wx.request({
        url: baseInfo.url+'/user/login',
        data: {
          code,
          avatarUrl,
          nickName
        },
        method: 'get',
        success: async res => {
          let {code,message,data} = res.data;
          if(code!=200){
            // console.log('登录失败!' + message);
            wx.showToast({
              title: `${message}`,
              icon: 'error',
              duration: 2000
            })
            return;
          }
          const token = data.token;
          const session_key = data.session_key;
          const user_id = data.user_id;
          const role_id = data.role_id;
          //将token存到全局
          app.globalData.token = token;
          app.globalData.session_key = session_key;
          app.globalData.user_id = user_id;
          app.globalData.role_id = role_id;
          //把值存放在微信的缓存内进行调用
          setToken(token);
          setUserInfo({nickName,avatarUrl});
          setSessionKey(session_key);
          setUserId(user_id);
          setRoleId(role_id);
          //取消登录提示
          wx.hideLoading();
          //关闭登录弹出窗口,子级发送数据给父级
          that.setData({ isHidden: true, errorSum: 0 });
          that.triggerEvent('onLoadFun',{nickName,avatarUrl,token});
        }
      })
    }
  },
})

wxml

<view class='Popup' hidden='{{isHidden}}'>
   <image src='../../assets/img/user-active.png'></image>
   <view class='title'>授权提醒</view>
   <view class='tip'>请授权头像等信息,以便为您提供更好的服务</view>
   <view class='bottom flex'>
      <view class='item' bindtap='close'>取消</view>
       <button class='item grant theme-icon-color-yellow' wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 去授权 </button>
       <button class='item grant theme-icon-color-yellow' wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 去授权 </button>
   </view>
</view>
<view class='mask' hidden='{{isHidden}}' catchtouchmove="true" bindtap='close'></view>

json文件

{
  "component":true
}

父级页面调用子级组件

js

handleAuth() {
    this.setData({
      isHidden: !this.data.isHidden
    })
  },

wxml

<view bind:tap="handleAuth">
                        <view class="login-login">
                            <text class="margin-right-10">登录</text>
                            <text class="margin-right-10">注册</text>
                            <icon class="icon iconfont icon-xinxi" style="font-size:44rpx"></icon>
                        </view>
                    </view>
                    <!--引用自定义组价并传值-->
                    <g-authorize bind:onLoadFun='onLoadFun' isGoIndex='{{isGoIndex}}' isHidden="{{isHidden}}" isAuto="{{isAuto}}"></g-authorize>

json

{
  "usingComponents": {
    "g-authorize": "/components/g-authorize/g-authorize",
  },
  "navigationBarTitleText": "我的"
}

参考网站:
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html

个人网站:沉默博客
如有错误,请多多指教。
如对你有帮助,给个赞吧。

上一篇:微信小程序---发送网络请求


下一篇:微信小程序基础学习(WXML)