uniapp 登录判断
时间: 2023-08-02 09:39:33 浏览: 43
要实现登录判断,可以使用uniapp中的全局变量和路由守卫。
1. 全局变量:在App.vue中定义一个全局变量isLogin,初始值为false,表示未登录。
2. 登录页:登录成功后将App.vue中的isLogin值改为true,并将token等用户信息存储到本地。
3. 路由守卫:在需要登录才能访问的页面中,使用路由守卫beforeEach()方法判断isLogin的值,如果为false,则跳转到登录页,否则继续访问页面。
示例代码如下:
在App.vue中定义全局变量isLogin:
```
export default {
data() {
return {
isLogin: false
}
}
}
```
登录成功后将isLogin值改为true,并存储用户信息:
```
// 登录页
login() {
// 登录成功后将isLogin值改为true
this.$root.isLogin = true
// 将用户信息存储到本地
uni.setStorageSync('token', 'xxxx')
uni.setStorageSync('userInfo', { name: 'xxx', avatar: 'xxx' })
}
```
在需要登录才能访问的页面中使用路由守卫判断isLogin的值:
```
// 路由守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !uni.getStorageSync('token')) {
next({ path: '/login' })
} else {
next()
}
})
```
其中,to.meta.requiresAuth表示该页面需要登录才能访问。如果isLogin的值为false,且用户未登录(即未存储token),则跳转到登录页;否则继续访问页面。