使用Vue实现简单的Tab控件

发布时间:2019-05-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用Vue实现简单的Tab控件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

使用Vue实现Tab功能。

创建一个tab.vue文件,内容如下:

<template>
  <div class="tab_box">
    <!--这里是tab的每一项-->
    <div v-for="item in tabs" :key="'tabItem' + item.id" :class="['tab_item', {'active_tab':currentTab === item.id}]" @click="changeTab(item.id)">
      {{item.label}}
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      currentTab: '' // 用于记录tab当前所在项的id
    }
  },
  props: ['tabs'], // 需要父组件传入
  methods: {
    changeTab (id) {
      this.currentTab = id
      this.$emit('changed', id) // 点击tab时触发changed方法,由父组件处理
    }
  },
  mounted: function () {
    this.currentTab = this.tabs[0].id // 默认下划线在第一项
  }
}
</script>
<style>
.tab_box{
  width:100%;
  display:table;
}
.tab_item{
  display:table-cell;
  padding: 3px 8px 4px 8px;
  /*如果想修改tab内的字体颜色和tab样式,在这里修改*/
}
.active_tab {
  /*这是下划线样式,可以根据需要修改*/
  border-bottom: 2px solid grey;
}
</style>

在父组件调用:

<tab @changed="change" :tabs="tabs"></tab>

其中change方法和tabs需要父组件中定义
tabs的格式如下:

tabs: [
        {'id': 't1', 'label': 'TAB1'},
        {'id': 't2', 'label': 'TAB2'},
        {'id': 't3', 'label': 'TAB3'},
        {'id': 't4', 'label': 'TAB4'},
        {'id': 't5', 'label': 'TAB5'}
      ],

为确保正确渲染,id需要保证唯一性。label为tab显示的内容。

change方法如下:

change (data) {
   //这里写切换tab之后你需要做的事,data为切换后的tabId
   this.message = 'this is ' + data + ', do whatever you want'
}

最终效果如下:

使用Vue实现简单的Tab控件

脚本宝典总结

以上是脚本宝典为你收集整理的使用Vue实现简单的Tab控件全部内容,希望文章能够帮你解决使用Vue实现简单的Tab控件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue