uniapp全局校验
uniapp全局校验的实现方法
在uniapp中实现全局校验通常涉及表单验证、权限校验或请求拦截等方面。以下是几种常见的全局校验方法:
表单全局验证
使用uni-forms组件结合自定义校验规则:
// 在main.js中设置全局规则
import uniForms from '@/components/uni-forms/uni-forms.vue'
Vue.component('uni-forms', uniForms)
Vue.prototype.$rules = {
required: (value, callback) => {
if (!value) {
callback(new Error('必填项'))
} else {
callback()
}
},
mobile: (value, callback) => {
if (!/^1[3-9]\d{9}$/.test(value)) {
callback(new Error('手机号格式错误'))
} else {
callback()
}
}
}
请求拦截校验
在uni.request前进行统一校验:
// 在main.js中封装请求
const request = (options) => {
// 添加token校验
if (!store.state.token && !options.noAuth) {
uni.showToast({ title: '请先登录', icon: 'none' })
return Promise.reject()
}
return uni.request(options)
}
Vue.prototype.$http = request
路由权限校验
通过拦截uni.navigateTo实现:
// 在main.js中重写导航方法
const originalNavigateTo = uni.navigateTo
uni.navigateTo = function(options) {
if (options.url.includes('/member/') && !store.state.token) {
uni.showToast({ title: '请先登录', icon: 'none' })
return uni.redirectTo({ url: '/pages/login/login' })
}
originalNavigateTo.call(uni, options)
}
自定义指令全局校验
创建全局校验指令:
// 在main.js中注册指令
Vue.directive('auth', {
inserted(el, binding) {
if (!store.state.token) {
el.style.display = 'none'
}
}
})
全局校验的注意事项
- 校验逻辑应尽量放在前端轻量级验证,重要校验仍需后端配合
- 对于复杂业务场景,建议使用专门的验证库如
vee-validate - 移动端校验需要优化错误提示方式,避免频繁弹窗影响体验
- 权限校验需要考虑游客模式和登录模式的不同场景
以上方法可以根据实际项目需求组合使用,构建完整的全局校验体系。对于大型项目,建议将校验逻辑模块化,方便维护和扩展。






