-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
NuxtTurnstile.vue
84 lines (70 loc) 路 1.85 KB
/
NuxtTurnstile.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<script setup lang="ts">
import type { TurnstileRenderOptions } from '../types'
import { nextTick, useRuntimeConfig, useNuxtApp, ref, onMounted, onBeforeUnmount } from '#imports'
const props = defineProps({
// eslint-disable-next-line vue/require-default-prop
modelValue: {
type: String,
required: false,
},
element: {
type: String,
default: 'div',
},
// eslint-disable-next-line vue/require-default-prop
siteKey: {
type: String,
required: false,
},
options: {
type: Object as () => Omit<TurnstileRenderOptions, 'callback'>,
default: () => ({}),
},
resetInterval: {
type: Number,
default: 1000 * 250,
},
})
const emit = defineEmits<{
(name: 'update:modelValue', token: string): void
}>()
const config = useRuntimeConfig().public.turnstile
const nuxtApp = useNuxtApp()
const el = ref()
const unmountStarted = ref(false)
let id: string | undefined = undefined
let interval: NodeJS.Timeout
const reset = () => {
if (id) {
nuxtApp.$turnstile.reset(id)
}
}
const unmount = () => {
unmountStarted.value = true
clearInterval(interval)
if (id) {
nuxtApp.$turnstile.remove(id)
}
}
onMounted(async () => {
await nextTick() // TODO: remove once upstream vue bug is fixed (https://github.com/vuejs/core/issues/5844, https://github.com/nuxt/nuxt/issues/13471)
id = await nuxtApp.$turnstile.render(el.value, {
sitekey: props.siteKey || config.siteKey,
...props.options,
callback: (token: string) => emit('update:modelValue', token),
})
interval = setInterval(reset, props.resetInterval)
if (unmountStarted.value) {
unmount()
}
})
onBeforeUnmount(unmount)
// This means we will have CF script server-rendered in our HTML
if (import.meta.server) {
nuxtApp.$turnstile.loadTurnstile()
}
defineExpose({ reset })
</script>
<template>
<component :is="element" ref="el" />
</template>