Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(unrefElement): don't return the Vue instance when $el is null/undefined #1657

Merged
merged 3 commits into from Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}