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 life cycle 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.

avatar
Sep 17th 2020

Please use getCurrentInstance.

import { getCurrentInstance } from 'vue'

onMounted(() => {
  const instance = getCurrentInstance()
})
avatar
Sep 17th 2020

Hi, thanks for your interest but Github issues are for bug reports and feature requests only. You can ask questions on the forum, the Discord server or StackOverflow.


In most scenarios, you would have everything accessible inside of setup. getCurrentInstance will help when migrating

avatar
Oct 10th 2020

Please use getCurrentInstance.

import { getCurrentInstance } from 'vue'

onMounted(() => {
  const instance = getCurrentInstance()
})

Is there any way to typing the return value of getCurrentInstance()?