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

157
Views
Can i reference global variables in a composable function?

I'm in the process of converting a project from Vue 2 options api to Vue 3 composition api. In a options api component i have a variable called componentData, and from this component i'm calling a mixin. When i call the mixin, i can access all the component's variables from inside of the mixin, here is an example:

//myMixin.js
export default {
    methods: {
        data_changed() {
            //where componentData is declared in the component
            console.log(this.componentData)
            this.componentData = [1, 2, 3]
        },
    data() {
        return {
            someVar: null
        }
    }
}

I'm having a lot of troubles doing the same with the composition api. Instead of mixins, i have composables, so say i have a component where i'm declaring a variable:

import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
        testData()
    }
}

And my composable useData.js:

export function testData() {
    console.log(componentData.value) //undefined
    componentData.value = [1, 2, 3] //will throw error
}

In this case, the composable will return undefined. How can i access the component's data without passing them as function parameters? Is that because in Vue3 composables are only supposed to return a value and they don't work the same as mixins? Is it possible to change the value of componentData from the composable?

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

You could pass the ref as an argument to testData():

// useData.js
export function testData(componentData) {
  componentData.value = [1, 2, 3] โœ…
}
// MyComponent.vue
import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
                     ๐Ÿ‘‡
        testData(componentData)
    }
}
about 4 years ago ยท Juan Pablo Isaza 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!