1,在根目录创建 components,然后在它里面创建一个authorization(随意 以后用当插件用)
2,在components/authorization目录中创建组件
a:完成结构
<!-- 用户未登录就不显示页面的内容 -->
<slot wx:if="{{ isShow }}"></slot>
b:完成逻辑
// components/authorization/index.js
Component({
// 使用组件时,要判断是否存在 token (如果存在,不管;不存在,跳转到登录页面)
attached() {
const token = getApp().token
this.setData({
isShow: token ? true : false,
})
if (!token) {
wx.reLaunch({ url: '/pages/login/index' })
return
}
},
})
c:在 app.json 中全局注册该组件
{
...
"usingComponents": {
"authorization": "./components/authorization/index",
}
...
}
d:在要使用的 wxml中使用
<authorization>
wxml内容
</authorization>
包起来 当isShow为 true 就显示 为 false就不显示
加强-登录检测 - 封装组件 - 保存未访问的页面
说明:
--未登录时,应该将本次访问的页面保存起来
--等到登录成功,再次跳转到这个页面中
--未访问的页面路径我们可以保存在登录的路径上
步骤:
--a:获取跳转的页面路径
--b:在跳转到登录页面时,保存到登录路径中
// components/authorization/index.js
Component({
// 使用组件时,要判断是否存在 token (如果存在,不管;不存在,跳转到登录页面)
attached() {
const token = getApp().token
this.setData({
isShow: token ? true : false,
})
if (!token) {
const pages = getCurrentPages() //getCurrentPages() 函数用于获取当前页面栈的实例
// 保存当前页面路径
const path = '/' + pages[pages.length - 1].route //固定写法
wx.reLaunch({ url: `/pages/login/index?redirectURL=${path}` })
return
}
},
})