actions,需要调用接口的话,假如页面想要调用actions中的方法获取数据,
必须使用try catch async await 进行包裹,详情看下面代码
import {defineStore} from 'pinia'
import {reqCode,reqUserLogin} from '../../api/hospital/index'
import {PhoneTy} from '../../api/hospital/type'
const useUserStore = defineStore('User',{
state:()=>{
return{
visiable: false,//用于控制登录组件的dialog显示与隐藏
code: '',//存储用户的验证码,
//存储用户的信息
userInfo:JSON.parse(localStorage.getItem('USERINFO') as string) || {}
}
},
actions:{
//获取短信验证
async getCode(value:string){
const r:PhoneTy = await reqCode(value) as any
if(r.code == 200){
this.code = r.data
console.log(this.code,'this.code1')
}
console.log(this.code,'this.code2')
},
//登陆用户
async reqUserLogin(value:object){
const r = await reqUserLogin(value)
this.userInfo = r.data
localStorage.setItem('USERINFO',JSON.stringify(this.userInfo))
console.log(r)
}
}
})
export default useUserStore
在页面中使用
引入pinia中的插件
import useUserStore from "../../store/modules/user";
let userStore = useUserStore();
//切记需要使用try catch,以及async await配合使用调用的接口,不然获取不到数据
//获取短信验证码
const getCode = async()=>{
console.log(loginParam.phone,'loginParam.value.phone')
try{
if(isPhone.value){
console.log(isPhone,'isPhone')
await userStore.getCode(loginParam.phone);
// userStore.getCode(loginParam.phone)
console.log(userStore.code,'userStore.code')
loginParam.code = userStore.code
flag.value = true;
}else{
return
}
}catch(error){
}
}