Clifton Labrum
Clifton Labrum

Reputation: 14168

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.

Upvotes: 12

Views: 25206

Answers (1)

wittgenstein
wittgenstein

Reputation: 4500

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>

Upvotes: 6

Related Questions