请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

为啥v-for循环tab-panel就不行?

//// Tabs.jsx
import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'Tabs',
  props: {
    defaultActiveKey: {
      type: String,
      default: ''
    }
  },
  emits: ['change'],
  setup(props, context) {
    const children = context.slots.default()
    const titles = children.map((panel) => {
      const { key, title } = panel.props || {}
      return {
        key,
        title
      }
    })

    const actKey = ref(props.defaultActiveKey)
    const changeActKey = (key) => {
      actKey.value = key
      context.emit('change', key)
    }

    const render = () => (
      <>
        <ul class="nav nav-tabs">
          {titles.map((item) => {
            const { key, title } = item
            return (
              <li class="nav-item">
                <button
                  key={key}
                  onClick={() => changeActKey(key)}
                  class="nav-link"
                  class={{ active: actKey.value === key }}
                >
                  {title}
                </button>
              </li>
            )
          })}
        </ul>

        <div class="tab-content">
          <div class="tab-pane fade show active">
            {children.find((panel) => {
              const { key } = panel.props || {}
              return actKey.value === key
            })}
          </div>
        </div>
      </>
    )

    return render
  }
})
//// TabPanel.vue
<template>
  <slot></slot>
</template>

<script setup>
defineProps({
  title: {
    type: String,
    default: ''
  }
})
</script>
//// 使用组件(写死 tab-panel 可以)
<script setup>
import Tabs from '@/components/Tab/Tabs.jsx'
import TabPanel from '@/components/Tab/TabPanel.vue'

const onTabsChange = (key) => {
  console.log('tab changed', key)
}
</script>

<template>
  <tabs default-active-key="1" @change="onTabsChange">
    <tab-panel key="1" title="tab1">
      <div>This is tab1 content...</div>
    </tab-panel>
    <tab-panel key="2" title="tab2">
      <div>This is tab2 content...</div>
    </tab-panel>
  </tabs>
</template>
//// 使用组件(v-for tab-panel 不行)
<script setup>
import Tabs from '@/components/Tab/Tabs.jsx'
import TabPanel from '@/components/Tab/TabPanel.vue'
import { ref } from 'vue'

const data = ref([
  {
    title: 'tab1',
    description: 'This is tab1 content...'
  },
  {
    title: 'tab2',
    description: 'This is tab2 content...'
  }
])

const onTabsChange = (key) => {
  console.log('tab changed', key)
}
</script>

<template>
  <tabs default-active-key="1" @change="onTabsChange">
    <tab-panel v-for="(item, k) in data" :key="k" :title="item.title">
      <div>{{ item.description }}</div>
    </tab-panel>
  </tabs>
</template>

正在回答 回答被采纳积分+3

1回答

双越 2022-06-12 10:10:34

这是哪里的问题呀,你咋往算法这里提?

我都乱了😁

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号