Skip to content

Commit

Permalink
feat: add useSafeOnMounted composable
Browse files Browse the repository at this point in the history
Workaround for vuejs/core#5844
  • Loading branch information
dankerow committed Sep 24, 2023
1 parent 10807cc commit 5d1e035
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/composables/useSafeOnMounted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Ref } from 'vue'
import { onMounted, onUnmounted } from 'vue'

export default (element: Ref<HTMLElement>, listener: () => void, checkTimeLimit = 100) => {
if (process.client) {
let timeId = 0
const checkInterval = 100
let checksLeft = checkTimeLimit / checkInterval

const check = () => {
if (element.value) {
listener()
} else {
if (checksLeft > 0) {
timeId = setTimeout(check, checkInterval)
checksLeft--
} else {
console.warn(`pass ${checkTimeLimit}ms, the element not ready! Please check.`)
}
}
};

onMounted(() => {
check()
})

onUnmounted(() => {
clearTimeout(timeId)
})
}
}

0 comments on commit 5d1e035

Please sign in to comment.