时间:2021-07-01 10:21:17 帮助过:17人阅读
简易版
tab对应的选项卡只是普通文本,多用于展示性组件。
复杂版
tab对应的选项卡包括表格,按钮,图标,表单等多种元素,包括数据交互、与父组件的通信等。
性能优化
切换tab时,缓存组件。
Prop
父组件向子组件传递参数。
tabList(tabs标题列表)、tabIndex(当前的tab序号)
自定义事件
切换tab事件
slot
内容分发
动态组件
keep-alive:如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染
如果是第一种需求,可以不必自己写组件,UI框架中现有的功能完全可以满足需求。
如果是第二种需求,一般没有完全合适的UI组件,而本例是我个人的一种解决方案。
封装tabs公共部分
tab对应的内容区域使用slot内容分发
ajax请求数据等操作是在分发内容组件中执行的。
钩子函数activated
通过activated监听组件是否激活。
template
<p class="my-tabs">
<p class="tabs-bar">
<p class="tabs-bar-nav">
<p class="tabs-tab" v-for="tab in tabList"
:class="[tabIndex == tab.index ? 'tabs-active' : '']"
@click="changeTab(tab)">
{{tab.name}}
</p>
</p>
</p>
<p class="tabs-content">
<slot></slot>
</p>
</p> export default {
name: 'MyTabs',
props:
{
tabList: Array,
tabIndex: Number
},
data () {
return {
}
},
methods: {
changeTab: function (tab) {
this.$emit('changeTab', tab)
}
}
}style
<style scoped lang="scss">
.my-tabs {
font-size: 14px;
color: #444;
}
.tabs-bar {
border-bottom: 1px solid #eee;
position: relative;
padding: 5px 0;
}
.tabs-bar-nav {
display: table;
margin-left: 35px;
position: absolute;
bottom: -1px;
}
.tabs-tab {
min-width: 110px;
padding: 5px 0;
position: relative;
display: inline-block;
text-align: center;
cursor: pointer;
}
.tabs-active {
border-top: 1px solid pink;
border-left: 1px solid pink;
border-right: 1px solid pink;
border-bottom: 1px solid #fff;
}
.tabs-content {
padding-left: 20px;
padding-right: 20px;
padding-bottom: 30px;
}
</style>以下one,two内部只是一个p。
<!-- Tabs -->
<my-tabs :tabList="tabList" :tabIndex="tabIndex" @changeTab="changeTab">
<keep-alive>
<component :is="currentContent">
</component>
</keep-alive>
</my-tabs>import MyTabs from '../componets/tabs.vue'
import One from './one.vue'
import Two from './two.vue'
export default {
name: 'Home',
components: {
MyTabs,
'one': One,
'two': Two
},
data () {
return {
tabIndex: 0,
currentContent: 'one',
tabList: [
{
index: 0,
name: '选项一',
component: 'one'
},
{
index: 1,
name: '选项二',
component: 'two'
}
]
}
},
methods: {
// 切换选项卡
changeTab: function (tab) {
this.tabIndex = tab.index
this.currentContent = tab.component
}
}
}
tabs.png
相关推荐:
Jquery封装tab自动切换效果的具体实现_jquery
Tab切换组件(选项卡功能)实例代码_jquery
以上就是vue怎么封装组件? vue tab切换组件封装的方法(附代码)的详细内容,更多请关注Gxl网其它相关文章!