有些时候,我们需要好几个组件进行来回切换,那么我们就需要借助Vue的<compoenent>元素和:is属性进行操作,下面开始演示。
父组件
<template>
<div class="demo">
<button
v-for="tab of tabs"
:key="tab"
:class="['tab-button', { active: currentTab === tab}]"
@click="currentTab=tab"
>{{ tab }}</button>
<component :is="currentTab"></component>
</div>
</template>
<script>
import Home from './components/Home.vue'
import Posts from './components/Posts.vue'
import Archive from './components/Archive.vue'
export default {
components: {
Home,
Posts,
Archive
},
data() {
return {
currentTab: 'Home',
tabs: ['Home', 'Posts', 'Archive']
}
}
}
</script>
<style>
.demo {
font-family: sans-serif;
border: 1px solid #eee;
border-radius: 2px;
padding: 20px 30px;
margin-top: 1em;
margin-bottom: 40px;
user-select: none;
overflow-x: auto;
}
.tab-button {
padding: 6px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ccc;
cursor: pointer;
background: #f0f0f0;
margin-bottom: -1px;
margin-right: -1px;
}
.tab-button:hover {
background: #e0e0e0;
}
.tab-button.active {
background: #e0e0e0;
}
.tab {
border: 1px solid #ccc;
padding: 10px;
}
</style>
子组件 Archive
<template>
<div class="tab">
Archive component
</div>
</template>
子组件 Posts
<template>
<div class="tab">
Posts component
</div>
</template>
子组件 Home
<template>
<div class="tab">
Home component
</div>
</template>




还没有评论,来说两句吧...