2

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();
  }
}
3
  • 1
    What's @composables/use-drivers? The problem is very specific to it. If it's yours, you need to design API the way it's more comfortable to use. Here you likely need to pass a single "context" object that contains relevant data. Could be a computed if you need to keep it reactive within the hook. "Could I" - no, and even if you could, accessing arbitrary variables from another scope would be an awful thing, design-wise, Commented Nov 6, 2021 at 18:18
  • Thanks. I’ll try with the computed approach tomorrow. And yeah, I was kinda looking for the “could/should I” answer to know it if was a good practice or not. Commented Nov 7, 2021 at 1:14
  • Oh. And inside the use-drivers, would be my API requests logic (get, store, update, delete), hypothetically speaking. Commented Nov 7, 2021 at 1:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.