@gladesinger/vue3-yandex-smartcaptcha

中文文档
1.0.1发布于 2025/12/19MITTypeScriptESM + CJS零依赖近 30 天下载 3032

Yandex Smart Captcha Vue component

原始使用文档
文档目录23 节
  1. Описание
  2. Установка
  3. Импорт компонента
  4. TypeScript Поддержка
  5. Доступные типы:
  6. Пропсы
  7. Эмиты
  8. Методы
  9. Примеры использования
  10. Обычная капча
  11. Невидимая капча
  12. Description
  13. Installation
  14. Usage
  15. Importing the Component
  16. TypeScript Support
  17. Available Types:
  18. Props
  19. Events
  20. Methods
  21. Usage Examples
  22. Regular Captcha
  23. Invisible Captcha

Yandex Smart Captcha Vue component

Vue 3 Yandex SmartCaptcha

Русская версия | English version

Описание

Компонент для работы с Yandex Smartcaptcha. Перед использованием нужно зарегистрироваться и получить ключ клиента. Вся документация капчи доступна по ссылке Yandex Smartcaptcha

Установка

Чтобы установить этот пакет, выполните следующую команду:

npm install @gladesinger/vue3-yandex-smartcaptcha@latest

Вы можете использовать компонент YandexSmartCaptcha в вашем Vue 3 проекте следующим образом:

Импорт компонента

Импортируйте компонент и используйте его в вашем файле Vue:

import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

Или зарегистрируйте его через плагин Vue:

import { createApp } from 'vue'
import App from './App.vue'
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

const app = createApp(App)
app.component('YandexSmartCaptcha', YandexSmartCaptcha)
app.mount('#app')

Для использования в Nuxt, оберните вызов компонента в ClientOnly.

TypeScript Поддержка

Компонент полностью поддерживает TypeScript и предоставляет типы для всех пропсов, эмитов и методов. Типы доступны через импорт:

import type { 
  IYandexSmartCaptchaProps,
  IYandexSmartCaptchaEmits,
  IYandexSmartCaptcha,
  TCaptchaEvents,
  TSupportedLanguages,
  TShieldPositions
} from '@gladesinger/vue3-yandex-smartcaptcha/types';

Доступные типы:

  • IYandexSmartCaptchaProps - типы для пропсов компонента
  • IYandexSmartCaptchaEmits - типы для эмитов компонента
  • IYandexSmartCaptcha - типы для методов и свойств компонента
  • TCaptchaEvents - типы для событий капчи
  • TSupportedLanguages - поддерживаемые языки
  • TShieldPositions - возможные позиции щита

Пропсы

Вот список доступных пропсов для компонента YandexSmartCaptcha:

ПропсТипЗначение по умолчаниюОписание
siteKeyString-Ключ клиентской части.
languageTSupportedLanguages'ru'Язык виджета. Возможные значения: 'ru', 'en', 'be', 'kk', 'tt', 'uk', 'uz', 'tr'.
testBooleanfalseВключение работы капчи в режиме тестирования. Пользователь всегда будет получать задание. Используйте только для отладки и тестирования.
webviewBooleanfalseЗапуск капчи в WebView для повышения точности оценки пользователей в мобильных приложениях.
invisibleBooleanfalseНевидимая капча.
shieldPositionTShieldPositions'bottom-right'Расположение блока с уведомлением об обработке данных. Доступные значения: 'top-left', 'center-left', 'bottom-left', 'top-right', 'center-right', 'bottom-right'.
hideShieldBooleanfalseСкрыть блок с уведомлением об обработке данных.
loadWidgetBooleantrueЗагружать виджет при монтировании компонента.
deferBooleantrueЗагружать скрипт с атрибутом defer.
asyncBooleanfalseЗагружать скрипт с атрибутом async.
useOldUrlBooleanfalseИспользовать старый smartcaptcha.yandexcloud.net адрес для загрузки скрипта.

Эмиты

Компонент YandexSmartCaptcha поддерживает следующие события:

СобытиеОписаниеАргумент
callbackФункция-обработчик, возвращает токен в случае успеха.token: string
onChallengeVisibleОткрытие всплывающего окна с заданием.() => void
onChallengeHiddenЗакрытие всплывающего окна с заданием.() => void
onNetworkErrorВозникла сетевая ошибка.error: { message: string }
onJavaScriptErrorВозникла критическая ошибка JS.error: { filename: string, message: string, col: number, line: number }
onSuccessУспешная валидация пользователя.token: string
onTokenExpiredТокен прохождения проверки стал невалидным.() => void

Методы

Компонент экспортирует следующие методы, которые можно использовать:

МетодОписаниеАргумент
getResponseВозвращает текущее значение токена пользователя.
executeЗапускает проверку пользователя. Используется для запуска невидимой капчи.
resetСбрасывает состояние виджета до начального.
destroyУдаляет виджет и созданные им обработчики.
subscribeПодписывает обработчики на определенные события виджета. Например, для отслеживания открытия и закрытия всплывающего окна с заданием.eventName: TCaptchaEvents, callbackFun: Function. Доступные события: 'challenge-visible', 'challenge-hidden', 'network-error', 'javascript-error', 'success', 'token-expired'.

Компонент также предоставляет значение widgetId.

Примеры использования

Обычная капча

JavaScript

<script setup>
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

const success = (token) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      siteKey="ваш_ключ_сайта"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
  </div>
</template>

TypeScript

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      siteKey="ваш_ключ_сайта"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
  </div>
</template>

TypeScript Nuxt 3

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <ClientOnly>
      <YandexSmartCaptcha 
        siteKey="ваш_ключ_сайта"
        @onSuccess="success"
        @onTokenExpired="expired"
      />
    </ClientOnly>
  </div>
</template>

Невидимая капча

JavaScript

<script setup>
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import { ref } from 'vue'

const yaCaptcha = ref(null)

const success = (token) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}

const fireCaptcha = () => {
  yaCaptcha.value.execute()
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      ref="yaCaptcha"
      siteKey="ваш_ключ_сайта"
      :invisible="true"
      shieldPosition="top-left"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
    <button @click="fireCaptcha">Тест</button>
  </div>
</template>

TypeScript

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'
import { ref } from 'vue'

const yaCaptcha = ref<IYandexSmartCaptcha | null>(null)

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}

const fireCaptcha = () => {
  yaCaptcha.value?.execute()
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      ref="yaCaptcha"
      siteKey="ваш_ключ_сайта"
      :invisible="true"
      shieldPosition="top-left"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
    <button @click="fireCaptcha">Тест</button>
  </div>
</template>

Description

This package brings a component for Yandex Smartcaptcha. Before using it you need to get the user token from the official website. Smartcaptcha documentation available here Yandex Smartcaptcha

Installation

To install this package, run the following command:

npm install @gladesinger/vue3-yandex-smartcaptcha@latest

Usage

You can use the YandexSmartCaptcha component in your Vue 3 project as follows:

Importing the Component

Import the component and use it in your Vue file:

import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

Or register it as a Vue plugin:

import { createApp } from 'vue'
import App from './App.vue'
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

const app = createApp(App)
app.component('YandexSmartCaptcha', YandexSmartCaptcha)
app.mount('#app')

For usage in Nuxt, wrap the component call in ClientOnly.

TypeScript Support

The component fully supports TypeScript and provides types for all props, emits, and methods. Types are available through import:

import type { 
  IYandexSmartCaptchaProps,
  IYandexSmartCaptchaEmits,
  IYandexSmartCaptcha,
  TCaptchaEvents,
  TSupportedLanguages,
  TShieldPositions
} from '@gladesinger/vue3-yandex-smartcaptcha/types';

Available Types:

  • IYandexSmartCaptchaProps - types for component props
  • IYandexSmartCaptchaEmits - types for component emits
  • IYandexSmartCaptcha - types for component methods and properties
  • TCaptchaEvents - types for captcha events
  • TSupportedLanguages - supported languages
  • TShieldPositions - possible shield positions

Props

Here is a list of available props for the YandexSmartCaptcha component:

PropTypeDefault ValueDescription
siteKeyString-Client-side key.
languageTSupportedLanguages'ru'Widget language. Available values: 'ru', 'en', 'be', 'kk', 'tt', 'uk', 'uz', 'tr'.
testBooleanfalseEnables captcha testing mode. The user will always receive a challenge. Use only for debugging and testing.
webviewBooleanfalseRuns the captcha in WebView to improve accuracy in mobile applications using WebView.
invisibleBooleanfalseInvisible captcha.
shieldPositionTShieldPositions'bottom-right'Position of the data processing notification block. Available values: 'top-left', 'center-left', 'bottom-left', 'top-right', 'center-right', 'bottom-right'.
hideShieldBooleanfalseHides the data processing notification block.
loadWidgetBooleantrueLoad the widget when the component is mounted.
deferBooleantrueLoad script with defer attribute.
asyncBooleanfalseLoad script with async attribute.
useOldUrlBooleanfalseUse old smartcaptcha.yandexcloud.net url for loading script.

Events

The YandexSmartCaptcha component supports the following events:

EventDescriptionArgument
callbackCallback function, returns the token on success.token: string
onChallengeVisibleChallenge window becomes visible.() => void
onChallengeHiddenChallenge window becomes hidden.() => void
onNetworkErrorNetwork error occurred.error: { message: string }
onJavaScriptErrorCritical JavaScript error occurred.error: { filename: string, message: string, col: number, line: number }
onSuccessSuccessful user validation.token: string
onTokenExpiredThe token has expired.() => void

Methods

The component exposes the following methods:

MethodDescriptionArgument
getResponseReturns the current value of the user's token.
executeStarts the user verification process. Used to trigger the invisible captcha.
resetResets the widget to its initial state.
destroyRemoves the widget and its handlers.
subscribeSubscribes handlers to specific widget events. For example, to track the opening and closing of the challenge window.eventName: TCaptchaEvents, callbackFun: Function. Available events: 'challenge-visible', 'challenge-hidden', 'network-error', 'javascript-error', 'success', 'token-expired'.

The component also exposes the widgetId state, if you need it for your case.

Usage Examples

Regular Captcha

JavaScript

<script setup>
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'

const success = (token) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      siteKey="your_site_key"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
  </div>
</template>

TypeScript

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      siteKey="your_site_key"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
  </div>
</template>

TypeScript Nuxt 3

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}
</script>

<template>
  <div>
    <ClientOnly>
      <YandexSmartCaptcha 
        siteKey="your_site_key"
        @onSuccess="success"
        @onTokenExpired="expired"
      />
    </ClientOnly>
  </div>
</template>

Invisible Captcha

JavaScript

<script setup>
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import { ref } from 'vue'

const yaCaptcha = ref(null)

const success = (token) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}

const fireCaptcha = () => {
  yaCaptcha.value.execute()
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      ref="yaCaptcha"
      siteKey="your_site_key"
      :invisible="true"
      shieldPosition="top-left"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
    <button @click="fireCaptcha">Test</button>
  </div>
</template>

TypeScript

<script setup lang="ts">
import { YandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha'
import type { IYandexSmartCaptcha } from '@gladesinger/vue3-yandex-smartcaptcha/types'
import { ref } from 'vue'

const yaCaptcha = ref<IYandexSmartCaptcha | null>(null)

const success = (token: string) => {
  console.log(token)
}

const expired = () => {
  console.log('expired')
}

const fireCaptcha = () => {
  yaCaptcha.value?.execute()
}
</script>

<template>
  <div>
    <YandexSmartCaptcha 
      ref="yaCaptcha"
      siteKey="your_site_key"
      :invisible="true"
      shieldPosition="top-left"
      @onSuccess="success"
      @onTokenExpired="expired"
    />
    <button @click="fireCaptcha">Test</button>
  </div>
</template>

版本与发布记录

@gladesinger/vue3-yandex-smartcaptcha 共发布 4 个版本,首次发布于 2024/08/06;过去 12 个月发布了 1 个版本。

版本发布日期距今
1.0.1latest2025/12/1910 个月前
1.0.02025/04/161.6 年前
0.0.22024/08/062 年前
0.0.12024/08/062 年前

关于 @gladesinger/vue3-yandex-smartcaptcha 的常见问题

@gladesinger/vue3-yandex-smartcaptcha 是什么?

Yandex Smart Captcha Vue component

如何安装 @gladesinger/vue3-yandex-smartcaptcha?

在项目目录运行 npm install @gladesinger/vue3-yandex-smartcaptcha,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:vue(^3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gladesinger/vue3-yandex-smartcaptcha 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gladesinger/vue3-yandex-smartcaptcha 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gladesinger/vue3-yandex-smartcaptcha 可以商用吗?

@gladesinger/vue3-yandex-smartcaptcha 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gladesinger/vue3-yandex-smartcaptcha 的下载量有多少?

根据 npm 官方下载统计,@gladesinger/vue3-yandex-smartcaptcha 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,032 次,日均约 101 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gladesinger/vue3-yandex-smartcaptcha 还在维护吗?

最新版本 1.0.1 发布于 2025/12/19(10 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 1 个;首次发布于 2024/08/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。