Global logic vuejs

 1. Composable context

2. using asyn composables

3. computed property uses and how it is different from methods

4. how to handle reactivity in vue3

5. vue directive

6. vue directive hooks

7. how do you handle a single root component 

8. SFC and uses

 

1. Composable Context

In Vue 3, composables are reusable functions that encapsulate reactive state and logic, allowing you to share behavior across components without mixins or higher-order components. The "composable context" refers to the environment within these functions, where you access reactive refs, computed properties, and lifecycle hooks using the Composition API.
For example:
import { ref, onMounted } from 'vue';

export function useCounter() {
  const count = ref(0);

  function increment() {
    count.value++;
  }

  onMounted(() => {
    console.log('Composable mounted');
  });

  return { count, increment };
}
This function can be reused in multiple components, creating a shared "composable context."

2. Using Async Composables

Async composables handle asynchronous logic within Vue’s Composition API. This is especially useful for fetching data or any async operation inside composable functions. You can use async/await combined with reactive refs.
Example:
import { ref } from 'vue';

export function useFetchData(url) {
  const data = ref(null);
  const error = ref(null);
  const loading = ref(true);

  async function fetchData() {
    loading.value = true;
    try {
      const response = await fetch(url);
      data.value = await response.json();
    } catch (e) {
      error.value = e;
    } finally {
      loading.value = false;
    }
  }

  fetchData();

  return { data, error, loading };
}
This makes data fetching reactive and composable across components.

3. Computed Property Uses and How It Differs from Methods

  • Computed Properties are reactive and cached based on their dependencies. They only recompute when the underlying reactive data changes.
  • Methods run every time they are called and do not cache their result.
Example difference:
const number = ref(5);

const doubledComputed = computed(() => number.value * 2); // cached  
function doubledMethod() { return number.value * 2; } // runs every call
Use computed properties when you want derived state that should update reactively and efficiently. Use methods when you need to perform an action repeatedly without caching.

4. How to Handle Reactivity in Vue 3

Vue 3’s reactivity system is based on Proxies and offers several APIs:
  • ref() makes primitive values reactive.
  • reactive() creates a reactive object.
  • computed() derives reactive data.
  • watch() observes reactive data for side effects.
Example:
const state = reactive({ count: 0 });

watch(() => state.count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`);
});
This system enables fine-grained tracking of dependencies to automatically update the DOM or trigger side effects.

5. Vue Directive

Vue directives are special HTML attributes with the v- prefix that apply reactive behavior to the DOM. The most used directive is v-model, v-if, v-for, and v-bind. They instruct Vue how to manipulate the DOM based on reactive data.
Example:
<input v-model="username" />
Here, v-model binds the input value reactively with the component’s data.

6. Vue Directive Hooks

When creating custom directives, Vue provides lifecycle hooks to manipulate the DOM directly:
  • created: called once when the directive is attached.
  • beforeMount: before the element is inserted.
  • mounted: after the element is inserted into the DOM.
  • beforeUpdate: before an update happens.
  • updated: after an update.
  • beforeUnmount: before element removal.
  • unmounted: after element removal.
Example custom directive:
app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

7. How Do You Handle a Single Root Component?

Vue 3 requires that each single file component (SFC) has a single root element to manage the virtual DOM tree efficiently and keep templates well-structured. If you want multiple root nodes, Vue 3 supports fragments which allow multiple sibling root nodes in a component, unlike Vue 2.
However, usually, you wrap children in a <div> or <template> element to maintain the single root. <template> is handy since it doesn’t render extra DOM nodes.

8. SFC (Single File Component) and Uses

SFC (.vue files) encapsulates template, script, and style in a single file, promoting maintainability and modularity. Key features include:
  • Scoped CSS
  • <script setup> syntax for concise Composition API usage
  • Support for custom blocks
  • Powerful tooling like hot-reload and type inference
Example SFC structure:
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue';

const message = ref('Hello Vue 3 SFC!');
</script>

<style scoped>
div {
  color: blue;
}
</style>
SFCs are the recommended approach for Vue app development due to their organizational clarity.

 

Comments

Popular posts from this blog

insightsoftware vue js

Apexon React.js Interview

TCS vue js