[小程序代码片段] 轮播图 tabbar setData 发送网络请求 input实时获取输入的值 wx.login 登录获取code 获取openid 授权获取用户信息

轮播图

    <swiper indicator-dots="true" autoplay="true" interval="1000" duration="500">
        <block wx:for="{
     
     {swiperArr}}" wx:key="index">
            <swiper-item>
                <image src='{
     
     {item}}' mode="widthFix"></image>
            </swiper-item>
        </block>
    </swiper>

tabbar

 "tabBar": {
    
    
    "color":"#000",
    "selectedColor": "#ff0000",
    "list": [
      {
    
    
        "pagePath": "pages/news/news",
        "text": "新闻",
        "iconPath":"static/img/fen1.png",
        "selectedIconPath": "static/img/fen2.png"
      },
      
      {
    
    
        "pagePath": "pages/mine/mine",
        "text": "我的",
        "iconPath":"static/img/mine1.png",
        "selectedIconPath": "static/img/mine2.png"
      }
    ]
  },

setData

 this.setData({
    
    
                newsdata:res.data
            })
 console.log(this.data.newsdata);

request.js

// 封装请求
  const  ajax = (url,method,data)=>{
    
    
  // 显示loading 
   wx.showLoading({
    
    
     title: '加载中',
   })
   return new Promise((resolve,reject)=>{
    
    
     wx.request({
    
    
       url: url, //仅为示例,并非真实的接口地址
       data:data,
       method:method,
       header: {
    
    
         'content-type': 'application/json' // 默认值
       },
       success (res) {
    
    
         // console.log(res.data)
         resolve(res.data)
         // 隐藏loading
         wx.hideLoading()
       },
       fail(err){
    
    
         reject(err)
       }
     })
   })
}

export default ajax

http.js

// 管理所有的请求
import ajax from './request'
// 首页热点新闻接口
export function newsHot(data){
    
    
  return ajax('https://mpapi.iynn.cn/api/v1/news/hot','get',data)
}


    onLoad: function (options) {
    
    
    // 有就传data,没有就传null
        newsHot(null).then((res)=>{
    
    
            console.log(33,res);
            this.setData({
    
    
                newsdata:res.data,
            })
            console.log(this.data.newsdata);
        });
       
    },

input实时获取输入的值

https://developers.weixin.qq.com/miniprogram/dev/component/input.html

 <input type="text" placeholder="搜索" bindinput="bindKeyInput"></input>


 data: {
    
    
     newsdata:[],
     inputValue:''

 },
bindKeyInput: function (e) {
    
    
    this.setData({
    
    
      inputValue: e.detail.value
    })
    console.log(this.data.inputValue);

  },

input回车,bindconfirm

 <input type="text" placeholder="搜索" bindinput="bindKeyInput" bindconfirm="bindKeyconfirm"></input>
bindKeyconfirm: function (e) {
    
    
        
    },

小程序登录

获取code

request_login.js

const wxLogin = () => {
    
    
  return new Promise((reslove,reject) => {
    
    
    wx.login({
    
    
      success(res) {
    
    
        if (res.code) {
    
    
          reslove(res.code)
        }
        else {
    
    
          reject({
    
     message: "登录失败" })
        }
      },
      fail(err) {
    
    
        reject(err)
      }
    })
  })
}

export default wxLogin

mine.js

import wxLogin from '../../utils/request_login'

mine.js


onLoad: function (options) {
    
    
    // 获取code
    this.getUserCode()

},
async getUserCode() {
    
    
       const code = await wxLogin();
       console.log(code);
   },

获取openid,登录

openid是用户身份的标识符,为了方便开发者识别用户的。其是一个字符串,包含了数字和字母。

openid有一个特征,同一个用户在使用很多个应用的时候,每个应用获取到这个用户的openid值是不一样的。例如,张三在使用App1,App1程序获取到其openid可能是123456789,App2获取到张三的openid可能是234567890。

想要获取openid,需要code(调用wx.login的api获得code),appid、appsecret。. 将code与appid及appsecret(后端)三个参数一起去腾讯换openid【由后端去换】

【后端要做】在换取到openid之后,去数据库中判断该openid是否存在(判断当前这个用户是新用户还是老用户),如果在则直接登录,如果不在后端会往数据库中建立一个用户账号。最终返回给前端openid及用户在项目中标识符(一般是用户名或用户id号)



config/config.js
存放通用的配置

const appid = "wxf8173895cc084401"
const appsecret = "826fd887304fbaffcf8e8b9ee3f5a73d"

export default {
    
    
    appid,
    appsecret
}

utils/http.js

// 登录接口
export function GetLogin(data){
    
    
  return ajax(base_url+'login','post',data)

}

mine.js

import {
    
    GetLogin} from '../../utils/http'
// 导入配置文件
import cfg from "../config/config"

mine.js


// 获取openid
getOpenId() {
    
    
    GetLogin({
    
    
        code: this.data.code,  //调用wx.login的api获得code
        appid: cfg.appid,
        appsecret: cfg.appsecret
    }).then(res => {
    
    
        
        this.setData({
    
    
            id: res.id,
            openid: res.data.openid
        })
      
        // 存储到缓存中
        wx.setStorageSync('openid', this.data.openid)
    })
},

授权获取用户信息

utils/request_userinfo.js

const wxUserProfile = () => {
    
    
  return new Promise((reslove,reject) => {
    
    
    wx.getUserProfile({
    
    
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
    
    
        console.log(res);
        reslove(res.userInfo)
      }
    })
  })
}

export default wxUserProfile

mine.js

import wxUserProfile from '../../utils/request_userinfo'

mine.js

// 获取用户信息
 async getUserInfo() {
    
    
        const userInfo = await wxUserProfile();
        this.setData({
    
    
            userInfo: userInfo,
            hasUserInfo: true
        });
        // 存储到缓存中
        wx.setStorageSync('userInfo', this.data.userInfo)
    },

登录

<view class="login-info" bindtap="loginHandler" >登录/注册</view>
    // 登录
    loginHandler() {
    
    
        // 获取缓存数据
        let openid = wx.getStorageSync('openid');
        if (!openid) {
    
    
            // 获取openid
            this.getOpenId()
        };
        // 获取用户信息
        let user_info = wx.getStorageSync('user_info');
        if (!user_info) {
    
    
            // 获取用户信息
            this.getUserInfo();
        }
    },

登录图示

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_14993591/article/details/121511336