Skip to content

Commit

Permalink
feat: slot
Browse files Browse the repository at this point in the history
  • Loading branch information
jaskang committed Jul 26, 2024
1 parent e6a7425 commit 129d7fd
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
2 changes: 1 addition & 1 deletion prettier.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default {
printWidth: 140,
printWidth: 120,
tabWidth: 2,
useTabs: false,
// 语句末尾分号
Expand Down
9 changes: 6 additions & 3 deletions src/_pure/ForwardSlot/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { cloneVNode, Comment, defineComponent, Fragment, mergeProps, type VNode } from 'vue'
import { useComponentRef } from '@/use/useComponentRef'

function renderSlotFragments(children?: VNode[]): VNode[] {
if (!children) return []
Expand All @@ -9,12 +10,14 @@ function renderSlotFragments(children?: VNode[]): VNode[] {
})
}

export const ForwardSlot = defineComponent({
export default defineComponent({
name: 'EForwardSlot',
props: { single: Boolean },
inheritAttrs: false,
setup(props, { attrs, slots }) {
setup(props, { attrs, slots, expose }) {
return () => {
const { componentRef, currentElement } = useComponentRef()
expose({ $el: currentElement })
if (!slots.default) return null

const children = renderSlotFragments(slots.default())
Expand All @@ -31,7 +34,7 @@ export const ForwardSlot = defineComponent({
// remove props ref from being inferred
delete firstNonCommentChildren.props?.ref

const mergedProps = firstNonCommentChildren.props ? mergeProps(attrs, firstNonCommentChildren.props) : attrs
const mergedProps = mergeProps(attrs, firstNonCommentChildren.props || {}, { ref: componentRef })
// remove class to prevent duplicated
if (attrs.class && firstNonCommentChildren.props?.class) delete firstNonCommentChildren.props.class
const cloned = cloneVNode(firstNonCommentChildren, mergedProps)
Expand Down
22 changes: 22 additions & 0 deletions src/_pure/ForwardSlot/tests/ForwardSlot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { defineComponent, ref } from 'vue'
import { mount } from '@vue/test-utils'
import { describe, expect, test } from 'vitest'
import ForwardSlot from '../index'

describe('ForwardSlot', () => {
test('slot ref element', async () => {
const slotRef = ref()
const wrapper = mount(
defineComponent({
template: '<ForwardSlot ref="slotRef" class="text-green"><span class="bg-red">test</span></ForwardSlot>',
components: { ForwardSlot },
setup() {
return { slotRef }
},
}),
{}
)
expect(slotRef.value.$el.tagName).toBe('SPAN')
expect(wrapper.html()).toBe('<span class="text-green bg-red">test</span>')
})
})

0 comments on commit 129d7fd

Please sign in to comment.