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

189
Visualizações
How to have data shared between Vue3 single file component instances?

I don't need to pass data between a parent component to a child one or the opposite, I need something like php/c static variables.

I want my sfc (single file component) to have some data that is shared among all instances in in the page.

As far as I understand that's why in sfc we define data as a function

export default {
    data(){
        return {
            // props here
        };
    }
}

while in page scripts we can define it as an object

const app = new Vue({
    data: {
        // props here
    },
}

That's because since we can have multiple instances of a sfc in the page defining its data as a function make each instance to execute in and get its own data, while with page script we can have a singe instance.

I need to define some of my sfc data to be shared between component instances, while other data to be per-instance.

Is there a way to do this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That depends on the data to be defined, its complexity, and purpose.

If these are 2 or 3 readonly variables, they can be set as global properties using Vue.prototype (Vue 2) or app.config.globalProperties (Vue 3). I'm not sure, because in your example you use Vue 2 syntax.

If the data should be reactive, you can set up a simple state management as explained in the Vue documentation: Simple state management.

If the data is more complex than that, the next step will be Vuex.

about 4 years ago · Juan Pablo Isaza Relatório

0

Following @Igor answer I looked after the simple state management and found the ref() method that creates reactive primitive values.

In my specific use case I needed to share among all the sfc instances just an array, so in my sfc I had:

const reactive_array = ref([]);

export default {
    data() {
        return {
            shared_array: reactive_array,
        };
    },
};
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