简体   繁体   中英

How to check slot or vnode type in vue3 render function?

I have a vue TabContiainer component, to use it in this way:

<TabContainer v-model="activeTab">
    <TabHeader tab-id="1"> tab1 </TabHeader>
    <TabHeader tab-id="2"> tab2 </TabHeader>
    <TabHeader tab-id="3"> tab3 </TabHeader>
    <TabContent tab-id="1"> content 1 </TabContent>
    <TabContent tab-id="2"> content 2 </TabContent>
    <TabContent tab-id="3"> content 3 </TabContent>
</TabContainer>

Work well.

this is TabContainer code:

import { h } from 'vue'
// import './TabContainer.scss' //ignore css

const TabContainer = {
  name: 'TabContainer',
  props: {
    modelValue: {
      type: String,
      required: true,
    },
  },
  render() {
    const slots = this.$slots.default()
    console.log(slots)
    // check slot type
    const existInValidSubCom = slots.some(slot => ![TabHeader, TabContent].includes(slot.type))
    if (existInValidSubCom) {
      const message = "TabContainer's sub commpont muse be  TabHeader and TabContent"
      // throw new Error(message)
      return h('div', message)
    }
    const Tabs = slots
      .filter(item => item.type === TabHeader)
      .map(Tab =>
        h(Tab, {
          class: {
            tab: true,
            active: Tab.props['tab-id'] === this.modelValue,
          },
          onClick: () => {
            this.$emit('update:modelValue', Tab.props['tab-id'])
          },
        }),
      )
    const content = slots.find(
      slot => slot.type === TabContent && slot.props['tab-id'] === this.modelValue,
    )
    return [h('div', { class: 'tab-container' }, Tabs), h('div', content)]
  },
}

export default TabContainer
export const TabHeader = TabItem({ name: 'TabHeader' })
export const TabContent = TabItem({ name: 'TabContent' })

function TabItem(options) {
  return {
    ...options,
    props: {
      tabId: {
        type: String,
        required: true,
      },
    },
    render() {
      return h('div', null, this.$slots.default())
    },
  }
}

if i add some comment in slot like this, it does not work,

<TabContainer v-model="activeTab">
    <TabHeader tab-id="1"> tab1 </TabHeader>
    <TabHeader tab-id="2"> tab2 </TabHeader>
    <TabHeader tab-id="3"> tab3 </TabHeader>
    <!-- some comment -->
    <TabContent tab-id="1"> content 1 </TabContent>
    <TabContent tab-id="2"> content 2 </TabContent>
    <TabContent tab-id="3"> content 3 </TabContent>
</TabContainer>

Some comments lead to following code get true in TabContainer

 // check slot type
const existInValidSubCom = slots.some(slot => ![TabHeader, TabContent].includes(slot.type))
  if (existInValidSubCom) {
    const message = "TabContainer's sub commpont muse be  TabHeader and TabContent"
    // throw new Error(message)
   return h('div', message)
}

Why do I need check sub component type? Like table tag, it is allowed to use limited tag in table, only thead tbody tr td. I hope there is such a limitation or similar feature between vue component.

console slots:

exist a Symbol(Comment).

It does not render as except. if i use v-for, same issue too.

<TabContainer v-model="activeTab">
    <TabHeader :tab-id="item" v-for="(item, index) in ['1', '2', '3']" :key="index">
      tab{{ item }}
    </TabHeader>
    <TabContent tab-id="1"> content 1 </TabContent>
    <TabContent tab-id="2"> content 2 </TabContent>
    <TabContent tab-id="3"> content 3 </TabContent>
</TabContainer>

slots have a Symbol(Fragment) vnode.

I am trying to find a good way to check vnode or slot type. But did not get a good one. Are there any better implement in my case? How can get it fixed?

check type with these code.

const vnodeList = this.$slots.default()
const childList = []
let existNonValidSubCom = false
let i = 0
do {
  const vnode = vnodeList[i]
  // html tag
  if (typeof vnode.type === 'string') {
    existNonValidSubCom = true
    break
  } else if ([TabHeader, TabContent].includes(vnode.type)) {
    childList.push(vnode)
  }
  else if (typeof vnode.type === 'symbol' && Array.isArray(vnode.children)) {
    // Symbol(Fragment)
    // childList.push(h(vnode.type, null, vnode.children))
    vnode.children.forEach(child => {
      if ([TabHeader, TabContent].includes(child.type)) {
        childList.push(child)
      }
    })
  }
  else if (typeof vnode.type === 'symbol' && typeof vnode.children === 'string') {
    // Symbol(Comment) skip
  } else {
    existNonValidSubCom = true
    break
  }
} while (++i < vnodeList.length && !existNonValidSubCom)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM