Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
Clifton Labrum Avatar asked Mar 16 '26 06:03

Clifton Labrum


1 Answers

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>
like image 167
wittgenstein Avatar answered Mar 18 '26 21:03

wittgenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!