其实这个问题不止在uniapp身上出现,很多用vue语法的都可能会出现问题,关键是在于对指针的了解。
业务场景:微信登录场景:需要调用微信的各类api。以下是代码初始展示。
getUserProfile(){
let code = '';
var that = this;
uni.showLoading({ title: '正在登录中' });
//调用微信获取code
uni.login({ provider:'weixin', success: (logRes) => { // console.log(logRes.code) code = logRes.code } });
uni.getUserProfile({ lang: 'zh_CN', desc: '用于核对员工注册资料信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success(user)
{
const data = { code:code, encryptedIv:user.iv, encryptedData:user.encryptedData }
// 登录用户信息
wxLogin(data).then(res => {
if(res.code===201){
}else if (res.code===200)
{ this.$store.dispatch('WxLogin', res.data.token).then(() => {
this.loginSuccess() })
}else{ return null; } }) },
fail(error){ console.log("error....",error) } })
uni.hideLoading();
主要的报错地方在以上标红地方,主要是调用vuex的store里面的方法报的错误,使用vuex并没有错误,错误的是this指向问题。出现错误的原因是我用了微信uniapp提供的api,uni.login和uni.getIserProfile两个方法,这会导致指针已经不再指向vue实例,而是指向回调函数本身。这会导致在回调函数中无法直接访问Vue实例的属性和方法。
解决方法,先上改动的代码
getUserProfile(){
uni.showLoading({
title: '正在登录中'
});
let code = '';
var that = this;
//调用微信获取code
uni.login({
provider:'weixin',
success: (logRes) => {
code = logRes.code
}
});
uni.getUserProfile({
lang: 'zh_CN',
desc: '用于核对员工注册资料信息',
success(user) {
const data = {
code:code,
encryptedIv:user.iv,
encryptedData:user.encryptedData
}
wxLogin(data).then(res => {
console.log(res)
if(res.code===201){
}else if (res.code===200){
that.$store.dispatch('WxLogin', res.data.token).then(() => {
that.loginSuccess()
})
}else{
return null;
}
})
},
fail(error){
console.log("error....",error)
}
})
uni.hideLoading();
},
其实解决方法很简单,只要在方法开始之前,先把指向存下来,var that = this;使用var变量提升,防止有其他bug的出现,存好了指向后,后续只要用tha.dispatch即可调用到vuex里的内容。