Subscribe on changes!

Access component instance from `onMounted` (or other lifeCycle hooks) callback

avatar
Sep 17th 2020

What problem does this feature solve?

I want to use composition api to register lifeCycle method which relies on component instance method.

For example, I want to create a onFontReady hook. Currently I can't have access to a component method.

// on-font-ready.js
import { onMounted } from 'vue'

export default function onFontReady (callback) {
  onMounted(() => {
    // although vm is available, I can't access it here
    document.fonts.ready.then(() => callback())
  })
}
// FontAwarableComponent.vue
export default {
  setup () {
    onFontReady(
      vm => vm.syncDOM() // won't work since onMounted has no access to component instance
    )
  }
  methods: {
    syncDOM () {
      // ...
    }
  }
}

What does the proposed API look like?

onMounted(vm => {
  vm.method()
})

Mixin should work however the composition is more elegant.