实现效果

  1. 实现类似elementui的效果

image.png

实现步骤

1. 先不封装组件

    <div class='tab'>
      <div class='tab-header'>
        <button>手机</button>
        <button>平板</button>
        <button>内容</button>
      </div>
      <div class='tab-body'>
        <div>手机内容</div>
        <div>平板内容</div>
        <div>电脑内容</div>
      </div>
    </div>

2. 注册一个全局组件

//comTab.vue

<template>
    <div class='tab-box'>
        <div class="tab-header">
            <button
                v-for='item in tabHeader' :key='item.id'
                @click="switchBtn(item)"
                :class='{active:activeName === item.name}'
                >{{item.label}}</button>
        </div>
        <div class="tab-body">
            <slot></slot>
        </div>
    </div>
</template>
<script>
export default {
  props: ['value'],
  data () {
    return {
      tabHeader: []
    }
  },
  computed: {
    activeName () {
      return this.value
    }
  },
  mounted () {
    this.tabHeader = this.$children
  },
  methods: {
    switchBtn (item) {
      this.$emit('input', item.name)
    }
  }
}
</script>

<style >
    button{
        outline: none;
    }
    .active{
        color: red;
    }
    .tab-header{
        height: 40px;
    }
    .tab-body{
        height: 200px;
        width: 200px;
        margin: auto;
        border: 1px solid #ccc;
    }
</style>

3.注册一个局部组件

//comTabPane.vue

<template>
    <div v-show="name === $parent.activeName ">
        <slot></slot>
    </div>
</template>
<script>
export default {
  props: ['label', 'name']
}
</script>

4.把组件注册到main.js

import comTab from './components/comTab'
import comTabPane from './components/comTabPane'

Vue.component('comTab', comTab)
Vue.component('comTabPane', comTabPane)

5.调用组件

<template>
  <div>
    <comTab v-model="activeName">
      <comTabPane label='手机' name='first'>
        手机内容
      </comTabPane>
      <comTabPane label='平板' name='second'>
        平板内容
      </comTabPane>
      <comTabPane label='电脑' name='third'>
        电脑内容
      </comTabPane>
    </comTab>
  </div>
</template>
<script>
export default {
  data () {
    return {
      activeName: 'first'
    }
  }
}
</script>

渣渣辉
1.3k 声望147 粉丝