Vue.js Composition API


What is the Composition API in Vue.js?

The Composition API is a feature introduced in Vue 3 that provides a new way to organize and reuse logic in Vue components. It allows developers to group related logic together using functions instead of the options object, making components more flexible and easier to maintain.


How do you set up a basic component using the Composition API?

You set up a basic component using the Composition API by importing the necessary functions from Vue, such as ref and computed, and then defining the setup function where you can define reactive state and computed properties.


import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const doubleCount = computed(() => count.value * 2);

    return { count, doubleCount };
  },
  template: `
    <div>
      <button @click="count++">Count: {{ count }}</button>
      <p>Double Count: {{ doubleCount }}</p>
    </div>
  `
};

What are refs in the Composition API?

Refs are a way to create reactive references to values in the Composition API. They are created using the ref function, allowing you to define reactive data that can be used in templates or other functions. The value can be accessed using the value property.


const count = ref(0);
console.log(count.value); // Accessing the value
count.value++; // Updating the value

How do you create computed properties using the Composition API?

You create computed properties using the computed function. This function takes a getter function and returns a reactive computed property that updates automatically when its dependencies change.


import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const doubleCount = computed(() => count.value * 2);

    return { count, doubleCount };
  }
};

What are the benefits of using the Composition API over the Options API?

Benefits of using the Composition API include:

  • Better Organization: Logic can be grouped together based on feature rather than by options (data, methods, etc.), leading to more maintainable code.
  • Reusability: Logic can be extracted into reusable functions (composables) that can be shared across components.
  • TypeScript Support: The Composition API provides better TypeScript support, making it easier to work with typed data.
  • Enhanced Flexibility: Allows for more complex interactions and state management patterns.

How do you use lifecycle hooks in the Composition API?

You can use lifecycle hooks in the Composition API by importing the relevant functions from Vue, such as onMounted, onBeforeUnmount, etc., and calling them within the setup function.


import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const message = ref('Hello, Vue!');

    onMounted(() => {
      console.log('Component mounted:', message.value);
    });

    onBeforeUnmount(() => {
      console.log('Component will be unmounted');
    });

    return { message };
  }
};

What are composables in Vue.js?

Composables are reusable functions that encapsulate specific logic using the Composition API. They allow you to share reactive state and functionality across different components in a clean and organized way.


import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  const reset = () => (count.value = 0);

  return { count, increment, reset };
}

// Using the composable in a component
import { useCounter } from './useCounter';

export default {
  setup() {
    const { count, increment, reset } = useCounter();
    return { count, increment, reset };
  }
};

How do you provide and inject values using the Composition API?

You can provide and inject values in Vue components using the provide and inject functions. This allows you to share data or functions between ancestor and descendant components without passing props.


import { provide, inject } from 'vue';

const Parent = {
  setup() {
    const message = 'Hello from Parent';
    provide('message', message);
  },
  template: '<Child />'
};

const Child = {
  setup() {
    const message = inject('message');
    return { message };
  },
  template: '<p>{{ message }}</p>'
};

How can you handle reactive state using the Composition API?

You can handle reactive state using the ref function to create reactive references for primitive values or the reactive function for creating a reactive object.


import { ref, reactive } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const state = reactive({ message: 'Hello' });

    const increment = () => {
      count.value++;
      state.message = 'Count updated!';
    };

    return { count, state, increment };
  }
};

What are the differences between ref and reactive?

The ref function creates a reactive reference to a single value (primitive type), while the reactive function creates a reactive object that tracks changes to all its properties. Use ref for primitives and reactive for complex objects.


const count = ref(0); // For primitive values
const state = reactive({ count: 0 }); // For objects
Ads