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

159
Visualizações
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 Respostas
Responde à pergunta

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 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