Blog>
Snippets

Sharing logic with Composition API

Provide an example of how to create reusable composition functions to share logic across components in Vue.js 3.
import { ref, computed } from 'vue';

// A reusable composition function
export function useCounter(initialValue = 0) {
    const count = ref(initialValue);

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

    function decrement() {
        count.value--;
    }

    return { count, increment, decrement };
}
This composition function allows components to share counter logic. It initializes a 'count' reactive ref, provides 'increment' and 'decrement' functions to modify its value, and returns them for use in components.
import { reactive, toRefs } from 'vue';

// A reusable composition function for tracking mouse position
export function useMouse() {
    const state = reactive({ x: 0, y: 0 });

    function updateMouse(e) {
        state.x = e.pageX;
        state.y = e.pageY;
    }

    window.addEventListener('mousemove', updateMouse);

    return { ...toRefs(state) };
}
This composition function provides mouse position tracking by creating a reactive state object for the x and y coordinates and updating them on 'mousemove' events. It returns the refs to these properties for use in components.
import { onMounted, onUnmounted, ref } from 'vue';
import { useMouse } from './mouseComposable';

export default {
  setup() {
    // Using the `useMouse` composable to get reactive mouse coordinates
    const { x, y } = useMouse();

    // Local state for the component
    const isActive = ref(false);

    onMounted(() => {
      isActive.value = true;
    });

    onUnmounted(() => {
      isActive.value = false;
    });

    // Exposing state and mouse coordinates to the template
    return { x, y, isActive };
  }
};
This Vue.js component uses the 'useMouse' composable to track the mouse position reactively. It also manages its own local state 'isActive' to determine if the component is mounted. The 'onMounted' and 'onUnmounted' lifecycle hooks update this local state.