vue3 写一个Tab组件

简易版Tab组件的实现代码

效果

博主不会制作gif,只能上截图了

Index.vue

<script setup>
  import {ref} from 'vue'
  import Tab from './Tab.vue'
  import TabItem from './TabItem.vue'

  const activeTab = ref('a')

  function handleClick(name) {
    // console.log(name);
  }
</script>

<template>
  <tab v-model="activeTab" @click="handleClick">
    <tab-item label='标签一' name='a'>This is tab a</tab-item>
    <tab-item label='标签二' name='b'>This is tab b</tab-item>
    <tab-item label='标签三' name='c'>This is tab c</tab-item>
  </tab>
</template>

Tab.vue

<script setup>
import {defineComponent, reactive, toRefs, ref, computed, watch, toRef, useSlots} from 'vue'

const props = defineProps({
  modelValue: [String, Number]
})

const emit = defineEmits(['update:modelValue', 'click'])

const slots = useSlots()

const tabList = computed(() => {
  if (!slots.default) return []
  return slots.default().map(item => ({
    name: item.props.name,
    label: item.props.label
  }))
})

const modelValue = toRef(props, 'modelValue')

function handleClick(name) {
  // 触发父组件更行value
  emit('update:modelValue', name)

  // 触发父组件上的点击事件。 传入name
  emit('click', name)
}
</script>

<template>
  <div>
    <ul class="title-wrap">
      <li 
        v-for="item in tabList" 
        :key="item" 
        :class="{active: modelValue == item.name}"
         @click.stop="handleClick(item.name)"
      >{{item.label}}</li>
    </ul>

    <div class="content-wrap">
      <slot />
    </div>
  </div>
</template>

<style scoped lang='scss'>
  .title-wrap{
  	padding: 0;
    margin: 0 auto;
    list-style: none;
    display: flex;
    flex-direction: row;
    & > li {
      min-width: 40px;
      padding: 8px;
      margin: 0 10px 0 0;
      border: 1px solid #666;
      &:last-child{
        margin: 0;
      }
      &.active {
        border: 1px solid rgba(12, 143, 230, 0.856);
        color: rgba(12, 143, 230, 0.856);
      }
    }
  }
</style>

TabItem.vue

<script setup>
import {getCurrentInstance, computed} from 'vue'
  const props = defineProps({
    label: {
      type: String,
      required: true,
    },
    name: {
      type: [String, Number],
      required: true,
    }
  })

  const parentModelValue = computed(() => getCurrentInstance().parent.props.modelValue)
</script>

<template>
  <div v-show="parentModelValue == props.name">
    <slot/>
  </div>
</template>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值