Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

641
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!