vue3中封装极验组件进行行为验证

1.引入初始化函数(gt4.js下载地址: https://static.geetest.com/v4/gt4.js)

<script src="gt4.js"></script>

注: 行为验证要求初始化在业务页面加载时同时初始化,否则验证无法读取用户在业务页面操作的行为数据,会导致验证策略失效。

2.封装验证组件

<template>
    <div class="captcha"></div>
  </template>
  
  <script setup>
  const props = defineProps({
    captchaConfig:Object
  });
  if(props.captchaConfig){
    window.initGeetest4(
        props.captchaConfig.config,
        props.captchaConfig.handler
    );
  }
  </script>

3.页面中去使用

<template>
    <a-form ref="formRef" :model="form" :rules="rules">
        <a-form-item name="username">
            <a-input allow-clear size="large" style="border-bottom: 1px solid #d9d9d9;" :bordered="false"
                v-model:value="form.username" :placeholder="t('login.username')">
                <template #prefix>
                    <user-outlined />
                </template>
            </a-input>
        </a-form-item>
        <a-form-item name="password">
            <a-input-password size="large" style="border-bottom: 1px solid #d9d9d9;" :bordered="false"
                v-model:value="form.password" :placeholder="t('login.password')">
                <template #prefix>
                    <lock-outlined />
                </template>
            </a-input-password>
        </a-form-item>
        <div id="captcha" :class="captchaConfig.config.product === 'bind' ? 'hideHeight' : ''">
                <GeetestCaptcha :captcha-config="captchaConfig" />
        </div>
        <a-form-item style="margin-bottom: 0;">
            <a-button block size="large" type="primary" :loading="loading" @click="showPopup">
                登录
            </a-button>
        </a-form-item>
        
    </a-form>
</template>
  
<script setup>
import GeetestCaptcha from '@/components/Geetest/GeetestCaptcha.vue'
import { ref, reactive, computed, unref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue/es';
import {
    UserOutlined,
    LockOutlined,
    SafetyCertificateOutlined,
    QqOutlined,
    WechatOutlined,
    WeiboOutlined
} from '@ant-design/icons-vue';
import I18nIcon from '@/layout/components/i18n-icon.vue';
import { getToken } from '@/utils/token-util';
import { goHomeRoute, cleanPageTabs } from '@/utils/page-tab-util';
import { login} from '@/api/login';
const { currentRoute } = useRouter();
const { t } = useI18n();
const formRef = ref(null);

// 加载状态
const loading = ref(false);
const captchaHandler = (captchaObj) => {
    window.captchaObj = captchaObj;
    captchaObj
        .appendTo("#captcha")
        .onReady(function () {
            console.log("ready");
        })
        .onNextReady(function () {
            console.log("nextReady");
        })
        .onBoxShow(function () {
            console.log("boxShow");
        })
        .onError(function (e) {
            console.log(e);
        })
        .onSuccess(function () {
            if (captchaConfig.config.product === "bind") {
                submit()
            }
        });
};
//配置极验验证参数
const captchaConfig = reactive({
    config: {
        captchaId: "********************",//实际你申请的captchaId
        product: "bind",
        // nativeButton: {
        //     height: '40px',
        //     width: '100%'
        // }
    },
    handler: captchaHandler,
});

// 表单数据
const form = reactive({
    username: 'admin',
    password: '123456',
});



// 表单验证规则
const rules = computed(() => {
    return {
        username: [
            {
                required: true,
                message: t('login.username'),
                type: 'string',
                trigger: 'blur'
            }
        ],
        password: [
            {
                required: true,
                message: t('login.password'),
                type: 'string',
                trigger: 'blur'
            }
        ]
    };
});
const showPopup =()=>{
    if (captchaConfig.config.product === "bind") {
        if (window.captchaObj) {
          window.captchaObj.showCaptcha();
        } else {
          alert("请等待验证初始化完成");
          return false;
        }
    }
}
/* 跳转到首页 */
const goHome = () => {
    const { query } = unref(currentRoute);
    goHomeRoute(query.from);
};
/* 提交 */
const submit = () => {
    if (!formRef.value) {
        return;
    }
    formRef.value.validate().then(() => {
        loading.value = true;
        login(form)
            .then(() => {
                message.success('登录成功');
                cleanPageTabs();
                goHome();
            })
            .catch((e) => {
                window.captchaObj.reset();
                message.error(e.message);
                loading.value = false;
            });

      

    });
};


</script>
  
<style lang="less" scoped>
.hideHeight {
    height: 0;
}




</style>
  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以尝试以下步骤来封装一个Vue 3和TypeScript下使用Element Plus的表单提交组件: 1. 安装必要的依赖: - Vue 3:`npm install vue@next` - TypeScript:`npm install -D typescript` - Element Plus:`npm install element-plus` 2. 创建一个新的Vue组件,并为其选择一个合适的名称,例如`FormSubmit.vue`。 3. 在`FormSubmit.vue`文件,导入必要的模块和样式: ```vue <template> <!-- 表单内容 --> </template> <script lang="ts"> import { defineComponent } from 'vue'; import { ElButton, ElForm, ElFormItem } from 'element-plus'; export default defineComponent({ components: { ElButton, ElForm, ElFormItem, }, }); </script> <style scoped> /* Element Plus 样式 */ @import 'element-plus/packages/theme-chalk/src/index.scss'; /* 自定义样式 */ /* ... */ </style> ``` 4. 在模板编写表单内容,并使用Element Plus的组件来构建表单: ```vue <template> <el-form ref="form" :model="formData" label-width="120px"> <el-form-item label="姓名" prop="name"> <el-input v-model="formData.name"></el-input> </el-form-item> <!-- 更多表单项 --> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </template> <script lang="ts"> // ... export default defineComponent({ // ... data() { return { formData: { name: '', // 更多表单字段 } }; }, methods: { submitForm() { // 表单提交逻辑 if (this.$refs.form.validate()) { // 表单验证通过,执行提交操作 // ... } } } }); </script> ``` 这样,你就可以使用封装好的表单提交组件来方便地处理表单提交了。你可以根据实际需求添加更多的表单项,并在`submitForm`方法实现你的提交逻辑。希望这可以帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值