Vue interview

Reusability

Composables and how to write good ones, the shared-state trap of module-level refs, a useFetch composable with cancellation, custom directives and when to use them, and Vue plugins.

From your Reusability — composables, directives, plugins note.

Know

  • Composables: useX functions packaging stateful logic; called synchronously in setup; accept refs or getters and read them with toValue(); return a plain object of refs; clean up what they start.
  • Shared state: state created inside the function is per component; at module level it's shared by every component, and on a server by every request.
  • Directives: for logic on one DOM element (focus, click outside, lazy images, tooltips); hooks mirror the lifecycle; vName in <script setup>, app.directive() globally; avoid on components.
  • Plugins: install(app, options) called by app.use(); register components and directives, app.provide values, configure app.config; Router, Pinia, i18n and Sentry work this way. Runtime only, once per app instance.

Fact check of your notes

Gotcha· The root-element warning belongs to directives

"Not recommended for use on custom components - Directives are only applied to the root element" sits under the composables best practices. It's a rule for custom directives: on a component they apply to its root element. Composables have no such limit.

Exercise

Exercise
  • Write the useFetch composable from the coding question and use it with a ref, a getter and a plain string.
  • Write a v-click-outside directive that closes a dropdown, and remove its listener in unmounted.

Be able to say

Be able to say· Composable, directive or plugin?

"A composable for reusable stateful logic in components, like fetching or form handling. A directive when the logic is about one DOM element and needs direct access to it, like focus or click-outside. A plugin for app-wide setup in one app.use(): registering components, providing values everywhere, or hooking the error handler."

Your notes

Open in Notes

Nothing yet. Notes filed here show up on this page and the section overview.