vue-tg

repository·main·Indexed 42 days ago

https://github.com/deptyped/vue-telegram

A lightweight Vue integration for Telegram Mini Apps and Widgets (version 0.10.0). It provides type-safe, reactive, and async-friendly access to the Telegram Bot API through built-in components and composables for theme management, viewport control, haptic feedback, and cloud storage. Includes support for Nuxt 3 and runtime feature checks via isVersionAtLeast to ensure compatibility across different Bot API versions.

Tokens
32.9K
Snippets
104
Records
133
Agent score
54%

What's inside vue-tg

  1. React to Telegram state changes using reactivity

    main

    Many fields in vue-tg are reactive. You can use standard Vue patterns like watch or computed to respond to changes in the Telegram environment, such as the isActive state of the Mini App.

    const miniApp = useMiniApp()
    
    watch(miniApp.isActive, (isActive) => {
      if (isActive)
        startUpdating()
      else
        stopUpdating()
    })
  2. Handle Bot API versioning and type safety

    main

    The library provides runtime feature support checks to prevent errors on clients with outdated Bot API versions. For features introduced in specific versions (e.g., DeviceStorage in Bot API 9.0), use isVersionAtLeast to guard your code.

    const deviceStorage = useDeviceStorage()
    
    // Guard against older clients
    if (deviceStorage.isVersionAtLeast('9.0')) {
      // Safe to use features introduced in 9.0
      deviceStorage.getItem('token')
    }
  3. Use async/await with Telegram methods

    main

    Most Telegram interaction methods support async/await, allowing you to write flat, readable code instead of nesting callbacks. While callback-style usage is still supported for compatibility, the modern approach is preferred.

    const miniApp = useMiniApp()
    const qrScanner = useQrScanner()
    const popup = usePopup()
    
    // Modern async/await flow
    const url = await qrScanner.show({ text: 'Scan URL' })
    const ok = await popup.showConfirm(`Open ${url}?`)
    if (ok) {
      miniApp.openLink(url)
    }
  4. Setup vue-tg with Nuxt 3

    main

    To use vue-tg in a Nuxt 3 application, follow these steps:

    1. Install the package: npm i vue-tg.
    2. Add the Telegram script: Include the script in your nuxt.config.ts under the app.head.script section.
    3. Client-side rendering: Because the Telegram Web App script relies on the browser environment, you must wrap your Telegram-related components in the <ClientOnly> component to prevent SSR errors.
    export default defineNuxtConfig({
      app: {
        head: {
          script: [{ src: 'https://telegram.org/js/telegram-web-app.js' }],
        },
      },
    })
    <template>
      <NuxtPage />
      <ClientOnly>
        <MiniApp />
      </ClientOnly>
    </template>
    
    <script setup lang="ts">
    import MiniApp from '~/components/MiniApp.vue'
    </script>
  5. Handle Telegram Mini App events

    main

    You can listen to Telegram Mini App events using two primary methods: direct event-handler functions or Vue composables.

    Method 1: Event-handler functions

    Event-handler functions follow the naming convention on<EventName> in camelCase. For example, the themeChanged event is handled via onThemeChanged.

    Method 2: Composables

    Most events are also exposed via composables, which often provide an .onChange(), .onStart(), or similar method for a more reactive experience.

    Managing Subscriptions

    By default, event handlers automatically unsubscribe when the Vue component unmounts. If you need to manage the lifecycle manually, you can use the manual: true option or call .off() on the returned handler.

    Warning: If you use { manual: true }, you are responsible for calling .off() to prevent memory leaks.

    // Using event-handler functions
    import { onThemeChanged } from 'vue-tg'
    
    onThemeChanged(() => {
      // handle theme update
    })
    
    // Using composables
    import { useTheme } from 'vue-tg'
    
    const theme = useTheme()
    
    theme.onChange(() => {
      // handle theme update
    })
    
    // Manual unsubscription
    const handler = onThemeChanged(() => {}, { manual: true })
    handler.off()
  6. Connect your Mini App to the Telegram client

    main

    To enable Telegram functionality, you must include the official Telegram Web App script in the <head> section of your HTML. This script must be placed before any other scripts to ensure the Telegram environment is initialized correctly.

    <script src="https://telegram.org/js/telegram-web-app.js"></script>
  7. Migrate from legacy WebApp composables to Mini App composables

    main

    The vue-tg library has updated its composable naming convention. Many composables prefixed with useWebApp are now deprecated in favor of shorter, more direct names. If you are using older versions or following outdated tutorials, you should migrate to the current API to ensure compatibility and follow best practices.

    Migration Mapping:

    DeprecatedCurrent
    useWebAppuseMiniApp
    useWebAppBackButtonuseBackButton
    useWebAppBiometricManageruseBiometricManager
    useWebAppClipboarduseClipboard
    useWebAppClosingConfirmationuseMiniApp
    useWebAppCloudStorageuseCloudStorage
    useWebAppHapticFeedbackuseHapticFeedback
    useWebAppMainButtonuseMainButton
    useWebAppNavigationuseMiniApp
    useWebAppPopupusePopup
    useWebAppQrScanneruseQrScanner
    useWebAppRequestsuseMiniApp
    useWebAppSettingsButtonuseSettingsButton
    useWebAppShareuseMiniApp
    useWebAppThemeuseTheme
    useWebAppViewportuseViewport
  8. Verify Telegram Mini App version compatibility

    main

    Telegram features are tied to specific Bot API versions. To prevent runtime errors when using features not yet supported by the user's Telegram client, use isVersionAtLeast from useMiniApp to perform a check.

    Alternatively, you can import composables from a version-specific entry point (e.g., vue-tg/7.8) to ensure the types and methods available match that version.

    Warning: Importing from vue-tg/latest skips version checks. This is useful for prototyping but can lead to crashes in production if the user's client is outdated.

    import { useMiniApp } from 'vue-tg'
    
    const miniApp = useMiniApp()
    
    // Check if version 7.8+ is supported before using shareToStory
    if (miniApp.isVersionAtLeast('7.8')) {
      miniApp.shareToStory("https://url-to-image")
    }
  9. Register the VueTelegramPlugin for global component aliases

    main

    Register the VueTelegramPlugin on your Vue instance to enable the use of global aliases for Telegram components. This allows you to use shorthand component names (e.g., <tg-alert />) instead of importing and using the full component names (e.g., <Alert />) in every template.

    import { VueTelegramPlugin } from 'vue-tg'
    
    Vue.use(VueTelegramPlugin)
  10. Install vue-tg as a Vue plugin

    main

    To use the Telegram components globally in your Vue application, install the VueTelegramPlugin. This registers all Telegram-related components with the Tg prefix (e.g., TgAlert, TgMainButton, TgLoginWidget).

    import { createApp } from 'vue'
    import { VueTelegramPlugin } from 'vue-tg'
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.use(VueTelegramPlugin)
    app.mount('#app')
  11. Migrate from useWebAppBiometricManager to useBiometricManager

    main

    The useWebAppBiometricManager composable is deprecated. Developers should migrate to the modern useBiometricManager API. The legacy version wraps useBiometricManager('8.0') and provides renamed properties and methods.

    When migrating, note the following mapping for key properties and methods:

    Legacy Property/MethodModern Equivalent
    isBiometricInitedisInited
    isBiometricAvailableisBiometricAvailable
    biometricTypebiometricType
    isBiometricAccessRequestedisAccessRequested
    isBiometricAccessGrantedisAccessGranted
    biometricDeviceIddeviceId
    isBiometricTokenSavedisBiometricTokenSaved
    initBiometricinit
    requestBiometricAccessrequestAccess
    authenticateBiometricauthenticate
    updateBiometricTokenupdateToken
    openBiometricSettingsopenSettings

    Additionally, the event listeners onBiometricManagerUpdated, onBiometricAuthRequested, and onBiometricTokenUpdated should be imported directly from vue-tg instead of being accessed through the legacy composable.