Home > Enterprise >  Access data on main component from composable - VueJS 3
Access data on main component from composable - VueJS 3

Time:11-08

I was wondering what could be the best approach to access data on my setup function, from a composable method... If it is possible at all (and a good practice).

For example, on my main component, I would have a reactive data object with all of the variables used in that component... but not all of them will be used by my composable.

Here's an example of what I'm trying to do (It's kinda like a model composable)...

Let's say that I have a useDrivers composable, and want to use its saveDriver method, something like this:

// all shortened for readability
import useDrivers from "@composables/use-drivers";
export default {
  setup() {
    const { saveDriver } = useDrivers();

    const data= reactive({
      foo: null,
      bar: null,
      accident: { ... },
      driver: { ... },
      anotherUsedVar: null,
    });

    // instead of doing something like this:
    saveDriver(driver, accident.id, anotherUsedVar);

    // or even worse:
    saveDriver(driver.name, driver.gender, driver.license, accident.id, anotherUserVar);

    // Could I, somehow, access my DATA const from inside my method?
    // but, again, without having to pass whatever amount of parameters
    saveDriver();
  }
}

CodePudding user response:

If data is static, it can be a single context object:

const context = { name: driver.name, ... };
saveDriver(context);

If data is supposed to stay reactive inside saveDriver, a computed ref could be passed:

const context = computed(() => ({ name: driver.name, ... });
saveDriver(context);

Then data needs to be processed inside saveDriver with usual composition API - computed, watch, etc.

  • Related