img

Nuxt3 Create a new Vue Composable

2024-04-04 0条评论 234次阅读 JavaScript


For Nuxt 3, create a new file inside the composables folder (create it if you don’t have it already) named useBrevoWidget.ts or any name you like:

declare global {
    interface Window {
        BrevoConversationsID: string
        BrevoConversations: any
    }
}

export const useBrevoWidget = () => {
    // Load widget on mount
    onMounted(() => {
        const script = document.createElement('script')
        script.async = true
        script.src = 'https://conversations-widget.brevo.com/brevo-conversations.js'
        window.BrevoConversationsID = 'YOUR_CONVERSATIONS_ID'

        script.onload = () => {
            window.BrevoConversations =
                window.BrevoConversations ||
                function () {
                    ;(window.BrevoConversations.q = window.BrevoConversations.q || []).push(arguments)
                }
        }

        if (document.head) {
            document.head.appendChild(script)
        }
    })

    // Destroy widget on unmount
    onBeforeUnmount(() => {
        window?.BrevoConversations('kill', true)
    })

    const openChat = () => {
        window?.BrevoConversations('openChat', true)
    }

    return { openChat }
}

Use your new composable 🎉

<template>
    <h1>Contact us</h1>
    <p>Click on the chat bubble</p>
</template>

<script setup lang="ts">
    useBrevoWidget()
</script>
<template>
    <h1>Contact us</h1>
    <p>Click on the chat bubble or click this button</p>
    <button @click="openChat">Open chat</button>
</template>

<script setup lang="ts">
    const { openChat } = useBrevoWidget()
</script>

💬 COMMENT


🦄 支持markdown语法

👋友