说明
验证码服务可自行去申请,不过好像是要企业才能申请,这里
结合uview组件库+mockjs在本地实现发送并获取验证码
配置
验证码组件u-verification-code官网不再维护,但不影响使用可在uniapp直接配置。
链接:https://pan.baidu.com/s/1XpJ5zPKLveUH57Zeod4dNg?pwd=bsso
提取码:bsso
在项目pages.json文件中配置好路径
"easycom": {
"^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue"
},
mockjs使用
根目录创建mock文件夹,分别创建mock/index.js,mock/code.json
index.js
import Mock from 'mockjs'
import code from './code.json'
Mock.mock('/mock/code',{code:200,data:code,msg:"获取验证码成功"})
code.json
[
"1234","4553","2346","9765","4567","4589","0087","4538","8796"
]
封装axios,创建请求api
根目录下创建utils
utils/mockRequest.js
import axios from '@/js_sdk/gangdiedao-uni-axios'
//根据自身情况引入axios
// 创建自定义接口服务实例
const http = axios.create({
baseURL: '/mock',//根据个人后端情况,修改此处baseURL
timeout: 6000, // 不可超过 manifest.json 中配置 networkTimeout的超时时间
withCredentials: true,
headers: {
'Content-Type': 'application/json',
//'X-Requested-With': 'XMLHttpRequest',
},
})
// 拦截器 在请求之前拦截 添加token
http.interceptors.request.use(config => {
//请求前有关处理逻辑
return config
})
// 响应后的拦截
http.interceptors.response.use(response => {
//响应拦截处理逻辑
return response;
}, error => {
return Promise.reject(error.message)
})
export default http
根目录创建api文件夹
api/index.js
import mockRequest from '@/utils/mockRequest.js'
//验证码
export const getCode = () => mockRequest.get('/code')
main.js注册全局api
import * as API from '@/api/index.js'
Vue.prototype.$API = API
前端调用
template
<u-input style="width: 300rpx" v-model="code" placeholder="请输入验证码" />
<view class="bd-primary xs orange br60 flex row-center" @click="sendSmsFun" hover-class="none">
<!-- 获取验证码 -->
<u-verification-code unique-key="register" ref="uCode" @change="codeChange">
</u-verification-code>
<view class="xs">{{codeTips}}</view>
</view>
script
async sendSmsFun() {
// if (!this.$refs.uCode.canGetCode) return
if (!this.registerForm.mobilePhoneNumber) {
this.$common.errorToShow('请填写手机号信息~');
return;
}
console.log("111");
const {
data: res
} = await this.$API.getCode()
console.log(res);
if (res.code == 200) {
this.$common.successToShow(res.msg)
this.$refs.uCode.start();
//获取随机验证码
var random = Math.floor(Math.random() * 9)
this.code = res.data[random]
}
},
codeChange(tip) {
this.codeTips = tip
},