因项目要兼容安卓APP,所以使用webview做成了一个组件
新建hybrid文件夹,创建要在webview引入的html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>验证码</title>
<style type="text/css">
.app {
width: 100%;
height: 50px;
padding: 20px 10px;
}
</style>
</head>
<body bgcolor="#121110">
<div class="app">
<!-- <img data-action="navigateBack" style="width: 50rpx;" src="../../static/common/Button_FangHui.png" mode="widthFix"> -->
<!-- <button class="btn" type="button" data-action="navigateBack">返回 </button> -->
</div>
<!-- uni 的 SDK -->
<!-- 需要把 uni.webview.1.5.4.js 下载到自己的服务器 -->
<script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script>
<script type="text/javascript" src="https://turing.captcha.qcloud.com/TCaptcha.js"></script>
<script>
document.addEventListener('UniAppJSBridgeReady', function() { //确认是否加载好了TencentCaptcha
let appid = 'xxxxx'; // 腾讯云控制台中对应这个项目的 appid
let callback = function(res) {
//下面方法h5和APP都可以调用 不行的话可以在网页端添加通信
// if(window && window.parent && window.parent.postMessage){
// console.log(res);
// window.parent.postMessage( res,'*');
// }
if (uni) {
uni.postMessage({
data: res
});
}
}
let captcha = new TencentCaptcha(appid, callback);
// 滑块显示
captcha.show();
//有返回按钮需要的可以添加点击事件,本项目做成组件获取到所需code后直接调用发送验证码api,下面方法不需要
document.querySelector('.app').addEventListener('click', function(evt) {
var target = evt.target;
var action = target.getAttribute('data-action');
switch (action) {
case 'navigateBack':
uni.navigateBack({
delta: 1
});
break;
default:
break;
}
});
});
</script>
</body>
</html>
创建vue组件
<template>
<view>
<web-view src="/hybrid/html/verification.html" @message="message" ></web-view>
</view>
</template>
<script setup lang="ts">
const $emit = defineEmits(['getCode'])
//h5端uniapp会触发这个事件
// #ifdef H5
window.addEventListener('message',function(e){
getCode(e.data.data.arg)
})
// #endif
//APP端uniapp会调用下面这个方法
const message = function(res) { //接收网页传给uniapp组件的参数
getCode(res.detail.data[0])
}
//向父组件传值
const getCode=(data) => {
$emit('getCode',data)
}
</script>
父组件引入验证组件并添加需要调用的方法
//父组件引入验证组件并添加需要调用的方法
<verificationVue v-if="isShowVerification" @getCode='getCode'></verificationVue>
import verificationCodeInput from '@/common/verificationCodeInput.vue'
本文参考https://blog.csdn.net/weixin_47403101/article/details/133070811