[Vuejs]-Issues with Vue.js Options API when injecting fetched data to other components

0👍

There’s no way how allCountries can be reactive this way, it’s used by value in data, before it’s assigned to res.

This is what ref pattern is for, it allows to use a reference instead of a value. It’s unnecessary to use Vue ref composition API for this purpose, a way it’s supposed to work in any Vue version is to pass an object everywhere.

In a parent:

  data() {
    return {
      allCountries: { value: [] }
    }
  },
  provide() {
    return {
      allCountries: this.allCountries
    }
  },
  methods: {
    fetchCountries() {
      ...
      this.allCountries.value = res
    }

In a child:

  inject: ['allCountries'],
  computed: {
    filteredCountries() { return this.allCountries.value }
  }

Unless there may be different provided values with the same name across the application, this is the case for a global store.

Leave a comment