1,uniapp实现微信小程序手机号快速登陆
看uniapp的官方文档,之前用的是uni.login会返回一个短code,后端是用不了的,后面通过询问才知道因该是使用button的方法@getphonenumber这样能够获取到手机号,并返回一个长code,这个后端才可以使用,用法如下
<button class="login-btn" type="primary" open-type="getPhoneNumber" @getphonenumber="getnumber">
微信用户一键登录
</button>
//获取用户手机号
const getnumber = async function (e) {
try {
console.log(e.detail.code);
} catch (error) {
// 错误处理逻辑
console.error('An error occurred while executing Captcha function:', error);
}
}
2.登陆后本地存储toekn
这次项目使用的是pinia存储token,使用pinia的时候使用错误了,刚开始一直存储不上,后面才发现是defineStore使用错误,
defineStore
接收两个参数id
: 唯一的标识,string
类型.Pinia
使用id
与开发者工具建立联系.- 第二个参数可以是一个函数, 也可以是一个对象.
刚开始直接复制另一个文件的definstore,只改了内容,后面发现是用不了,才知道是id重复了
本地存储token
//登录成功调用这个方法
const loginSuccess = (profile) => {
// 保存会员信息
useloginStore.setProfile(profile)
// 成功提示
uni.showToast({
title: '登录成功',
icon: 'success',
mask: true,
})
setTimeout(() => {
// 页面跳转
uni.navigateBack()
}, 500)
}
//pinia存储token
import { defineStore } from 'pinia';
import { ref } from 'vue';
// 定义 Store
export const loginStore = defineStore(
'login',
() => {
// 会员信息
const profile = ref();
// 保存会员信息,登录时使用
const setProfile = (val) => {
profile.value = val;
console.log(profile.value, 111111111111111111111);
};
// 清理会员信息,退出时使用
const clearProfile = () => {
profile.value = undefined;
};
// 记得 return
return {
profile,
setProfile,
clearProfile,
};
},
// TODO: 持久化
{
// 网页端配置
// persist: true,
// 小程序端配置
persist: {
storage: {
getItem(key) {
return uni.getStorageSync(key);
},
setItem(key, value) {
uni.setStorageSync(key, value);
},
},
},
}
);
//使用token
const useloginStore = loginStore();
const token = useloginStore.profile;
if (token) {
options.header.Authorization = `Bearer ${token}`;
}
3.在uniapp里给组件添加ref获取不到组件实例
使用 uniapp 的 原生方法uni.createSelectorQuery()
作用:返回一个 SelectorQuery
对象实例。可以在这个实例上使用 select
等方法选择节点,并使用 boundingClientRect
等方法选择需要查询的信息。
Tips:
- 使用
uni.createSelectorQuery()
需要在生命周期mounted
后进行调用。 - 默认需要使用到
selectorQuery.in
方法。