Vue实现点击列表切换并改变颜色
实现效果图如下 通过Vue的父子组件传值实现效果,单击切换颜色会进性改变并添加下划线
父组件代码实现(Home.vue)
需要进性对子组件的导入 import TabControl from ‘@/components/content/TabControl’
<tab-control
:titles="['流行','新款','经典']"
class="tab-control"
/>
js代码
<script>
import TabControl from '@/components/content/TabControl'
export default {
name: 'Home',
data () {
return {
}
},
components: {
TabControl
}
}
</script>
子组件代码实现(TabControl.vue)
<div id="tab-control">
<div
class="tab-control-item"
v-for="(item,index) in titles"
:key="index"
:class="{active:index===currentIndex}"
@click="tabcontrol(index)"
>
<span>{{item}}</span>
</div>
</div>
js
<script>
export default {
props: {
titles: {
type: Array,
default: function () {
return []
}
}
},
data () {
return {
currentIndex: 0
}
},
methods: {
tabcontrol (index) {
this.currentIndex = index;
}
}
}
</script>
CSS代码
<style scoped>
#tab-control {
display: flex;
width: 100%;
font-size: 15px;
text-align: center;
background-color: #fff;
height: 40px;
line-height: 40px;
}
.tab-control-item {
flex: 1;
}
.tab-control-item span {
padding: 5px;
}
.active {
color: var(--color-high-text);
}
.active span {
border-bottom: 3px solid #ff5777;
}
如何将列表固定到某一个位置使用定位实现
只需要对标签添加如下:
.tab-control {
position: sticky;
top: 44px;
}
效果图
|