Skip to content

Commit

Permalink
fix(unrefElement): don't return the Vue instance when $el is null
Browse files Browse the repository at this point in the history
…/`undefined` (#1657)

Co-authored-by: DrJume <DrJume@users.noreply.github.com>
  • Loading branch information
DrJume and DrJume committed Jun 16, 2022
1 parent a6564db commit 050da20
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
72 changes: 72 additions & 0 deletions packages/core/unrefElement/index.test.ts
@@ -0,0 +1,72 @@
import { defineComponent, h, nextTick, onMounted, ref } from 'vue-demi'
import { mount } from '../../.test'
import { templateRef } from '../templateRef'
import { unrefElement } from '.'

describe('unrefElement', () => {
it('should be defined', () => {
expect(unrefElement).toBeDefined()
})

it('works with regular html elements', () => {
const refKey = 'target'

mount(defineComponent({
setup() {
const targetEl = templateRef(refKey)

expect(unrefElement(targetEl)).toBeNull()

onMounted(() => {
expect(unrefElement(targetEl)).toBeInstanceOf(HTMLElement)
})

return { targetEl }
},
render() {
return h('div', { ref: refKey })
},
}))
})

it('works with Vue components which expose a proxy $el', () => {
const helperComponent = defineComponent({
props: {
text: String,
},
setup(props, { expose }) {
const buttonRef = ref<HTMLButtonElement | null>(null)

expose({ $el: buttonRef })

return () => [
props.text && h('button', { ref: buttonRef }),
h('p', props.text),
]
},

})

mount(defineComponent({
setup() {
const targetEl = ref<InstanceType<typeof helperComponent> | null>(null)
const myText = ref('')

expect(unrefElement(targetEl)).toBeNull()

onMounted(() => {
expect(targetEl.value?.$el).toBeNull()
expect(unrefElement(targetEl)).toEqual(targetEl.value?.$el)

myText.value = 'Hello'
nextTick(() => {
expect(targetEl.value?.$el).not.toBeNull()
expect(unrefElement(targetEl)).toEqual(targetEl.value?.$el)
})
})

return () => h(helperComponent, { ref: targetEl, text: myText.value })
},
}))
})
})
3 changes: 2 additions & 1 deletion packages/core/unrefElement/index.ts
Expand Up @@ -15,5 +15,6 @@ export type UnRefElementReturn<T extends MaybeElement = MaybeElement> = T extend
*/
export function unrefElement<T extends MaybeElement>(elRef: MaybeElementRef<T>): UnRefElementReturn<T> {
const plain = unref(elRef)
return (plain as VueInstance)?.$el ?? plain

return plain != null && '$el' in (plain as VueInstance) ? (plain as VueInstance).$el : plain
}

0 comments on commit 050da20

Please sign in to comment.