本示例结合了uview的u-mask组件
一、包装成验证码组件
1.新建组件aliyun-verify组件
<template>
<!-- 阿里云验证码模态框 -->
<u-mask :show="isShow" :mask-click-able="false" :z-index="999999">
<view class="aliyun-verify-wrap">
<view class="verify-show-wrap">
<view class="verify-title">请点击按钮验证</view>
<view id="ic"> </view>
<view class="close-btn" @tap.stop="close">关闭</view>
</view>
</view>
</u-mask>
<!-- 阿里云验证码模态框 -->
</template>
<script>
//加载js
let script = document.createElement('script')
script.src = 'https://g.alicdn.com/AWSC/AWSC/awsc.js'
document.body.appendChild(script)
export default {
data() {
return {
//是否显示
isShow: false,
//阿里云验证对象
aliyunIC: null,
//配置参数
params: {
//应用类型标识
appkey: 'xxxxxx',
//使用场景标识
scene: 'xxxxxxx'
}
}
},
methods: {
//显示
show() {
this.isShow = true
this.initComp()
},
//关闭
close() {
this.isShow = false
},
//初始化方法
initComp() {
if (this.aliyunIC) {
//调用重置方法
this.aliyunIC.reset()
return
}
const _this = this
AWSC.use('ic', function (state, module) {
//配置项
let icOption = {
// 应用类型标识。它和使用场景标识(scene字段)一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的appkey字段值,请务必正确填写。
appkey: _this.params.appkey,
// 使用场景标识。它和应用类型标识(appkey字段)一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的scene值,请务必正确填写。
scene: _this.params.scene,
// 声明智能验证需要渲染的目标元素ID。
renderTo: 'ic',
// 验证通过时会触发该回调参数。您可以在该回调参数中将会话ID(sessionId)、签名串(sig)、请求唯一标识(token)字段记录下来,随业务请求一同发送至您的服务端调用验签。
success: function (data) {
_this.$emit('success', data)
//验证成功后关闭弹窗
_this.close()
},
// 验证失败时触发该回调参数
fail: function (failCode) {
console.log(failCode)
},
// 验证码加载异常时触发该回调参数
error: function (errorCode) {
console.log(errorCode)
}
} // 智能验证的初始化参数对象
// 初始化 调用module.init对智能验证进行初始化
_this.aliyunIC = module.init(icOption)
})
}
}
}
</script>
<style lang="scss" scoped>
.aliyun-verify-wrap {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.verify-show-wrap {
background: #ffffff;
width: 680rpx;
padding: 40rpx 0rpx;
border-radius: 12rpx;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
.verify-title {
margin-bottom: 40rpx;
font-size: 40rpx;
font-weight: 500;
}
.close-btn {
width: 390rpx;
height: 88rpx;
background: linear-gradient(180deg, #00de76 0%, #3a9afa 100%);
border-radius: 44rpx;
color: #ffffff;
margin-top: 40rpx;
display: flex;
justify-content: center;
align-items: center;
}
}
}
</style>
二、使用
1.引入组件
//导入智能验证码组件
import aliyunVerify from '@/components/verify-code/aliyun-verify'
components: {
aliyunVerify,
...
},
2.模板中添加组件
<!-- 智能验证组件 -->
<aliyun-verify ref="aliyunVerify" @success="handleVerifySuccess" />
<!-- 智能验证组件 -->
3.验证成功回调方法
//验证成功回调
handleVerifySuccess(res) {
//验证成功后返回sessionId、sig、token 一并提交给业务服务器
//由业务服务器提交给阿里云服务器进行二次验证
console.log('======success=======')
console.log(res)
console.log('======success=======')
}
4.显示组件
this.$refs.aliyunVerify.show()
三、效果

网友评论