Search code examples
javascriptvue.jsvuejs3refvue-script-setup

Vue3 use ref from third party package in setup script


I'm using Vue 3 for my project and need to get use a ref from a third-party ReCaptcha package during the submission of a form. The code does not recognize the ref name since I did not personally create this ref:

async function submitContact() {
  const token = await mrecaptcha.getToken();
...

'mrecaptcha' is not defined.

It's used in the template like this:

<recaptcha v-if="isClient" ref="mrecaptcha" :site-key="siteKey" />

Usage can be found in the docs for this package here: https://www.npmjs.com/package/@appsbd/vue3-recaptcha


Solution

  • You need to create a ref in the script to get the element reference of recaptcha.

    const mrecaptcha = ref(null)
    

    Ex:

    <script setup>
    const mrecaptcha = ref(null)
    
    onMounted(() => {
      console.log(mrecaptcha)
    })
    </script>