DEV Community

Discussion on: Hooks are coming to Vue.js version 3.0

Collapse
 
pierresaid profile image
pierresaid

Will this not be redundant with the new composition Api : logic-extraction-and-reuse ?

example : mouse position tracking

import { ref, onMounted, onUnmounted } from 'vue'

export function useMousePosition() {
  const x = ref(0)
  const y = ref(0)

  function update(e) {
    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => {
    window.addEventListener('mousemove', update)
  })

  onUnmounted(() => {
    window.removeEventListener('mousemove', update)
  })

  return { x, y }
}

and then use it in a component

import { useMousePosition } from './mouse'

export default {
  setup() {
    const { x, y } = useMousePosition()
    // other logic...
    return { x, y }
  }
}