Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

639
Visualizações
Vue 3: How to Access Setup Variable in Component Function

Consider the following simple example using the composition API in Vue 3. I'm trying to have an instance of test available in the functions of my component.

<script>
import { defineComponent, ref, onMounted } from 'vue'

export default defineComponent({
  name: 'Test',
  setup(){
    let test = ref()
    
    onMounted(() => {
      doSomething()
    })

    return{
      test,
      doSomething
    }
  }
})

function doSomething(){
  console.log(test) //<-- undefined
  console.log(this.test) //<-- undefined
}
</script>

How do I access test inside doSomething()? My understanding is that anything returned by setup() should be available throughout the component much like a data() attributes from the options API.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

you have to pass the ref as a parameter

<script>
import { defineComponent, ref, onMounted } from 'vue'

export default defineComponent({
  name: 'Test',
  setup () {
    let test = ref(null)

    onMounted(() => {
      doSomething(test.value)
    })

    return {
      test,
      doSomething
    }
  }
})

function doSomething (param) {
  console.log(param); // null
}
</script>

another approach:

// functions.js
import { ref } from 'vue'
export let test = ref(null)
// vue-file
<script>
import { defineComponent, ref, onMounted } from 'vue'
import { test } from '../utils/functions.js'

export default defineComponent({
  name: 'Test',
  setup () {

    onMounted(() => {
      doSomething(test)
    })

    return {
      test,
      doSomething
    }
  }
})

function doSomething (param) {
  console.log(test.value); // <-- instant access
  console.log(param.value); // <-- import via parameter
}
</script>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda