uniapp全局校验
uniapp全局校验的实现方法
在uniapp中实现全局校验可以通过多种方式,主要包括拦截器、全局混入和自定义指令等方法。
使用请求拦截器进行校验
在main.js中配置请求拦截器,对所有请求进行统一校验:
// main.js
uni.addInterceptor('request', {
invoke(args) {
// 校验逻辑
if (!checkTokenValid()) {
uni.showToast({ title: '请先登录', icon: 'none' })
return Promise.reject('未登录')
}
return args
},
fail(err) {
console.error('请求失败', err)
}
})
使用全局混入(mixin)
创建全局mixin文件并在main.js中引入:
// mixins/globalMixin.js
export default {
methods: {
$globalCheck() {
if (!this.$store.getters.isLogin) {
uni.showToast({ title: '请先登录', icon: 'none' })
return false
}
return true
}
}
}
// main.js
import globalMixin from './mixins/globalMixin'
Vue.mixin(globalMixin)
页面路由拦截
在pages.json中配置页面路由守卫:
{
"easycom": {
"autoscan": true,
"custom": {
"^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
}
},
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
}
}
自定义指令校验
创建全局自定义指令进行校验:
// main.js
Vue.directive('auth', {
inserted(el, binding) {
if (!checkAuth(binding.value)) {
el.style.display = 'none'
uni.showToast({ title: '无权限访问', icon: 'none' })
}
}
})
状态管理配合校验
结合Vuex进行全局状态管理:
// store/index.js
export default new Vuex.Store({
state: {
token: null
},
getters: {
isLogin: state => !!state.token
}
})
// 页面中使用
if (!this.$store.getters.isLogin) {
uni.redirectTo({ url: '/pages/login/login' })
}
注意事项
- 拦截器会影响所有请求,需谨慎处理
- 全局混入的方法会注入到所有组件中,注意命名冲突
- 路由拦截需要根据实际业务需求配置
- 自定义指令适合处理DOM级别的权限控制
- 状态管理适合需要持久化的校验数据
以上方法可根据项目需求单独使用或组合使用,实现不同层次的全局校验功能。







