vue动态修改css样式:class
在vue中使用:class属性动态修改样式
<template> <view> <!-- 小菜单列表轮播 --> <view> <swiper class="swiper" :autoplay="false" @change="changeFun"> <block v-for="(item,index) in menuSwiper" :key="index" > <swiper-item> <view class="swiper-item"> <block v-for="(menu, index) in item" :key="index" > <view class="menu-cont"> <image :src="menu.url" mode="widthFix" ></image> <text>{{menu.name}}</text> </view> </block> </view> </swiper-item> </block> <!-- <swiper-item> <view class="swiper-item uni-bg-green">B</view> </swiper-item> --> </swiper> <view class="instruct-view"> <block v-for="(item, index) in instructData" :key="index"> <view class="instruct" :class="[index == num ? 'activeclass':'instruct']" ></view> </block> </view> </view> </view> </template> <script> export default { data() { return { instructData: ['', ''], num: 0, menuSwiper: [{}], //初始化一个二维数组 menuList:[ { url: "../../../static/images/tabbar/home-selected.png", name: "美食" }, { url: "../../../static/images/tabbar/home-selected.png", name: "城市便利" }, { url: "../../../static/images/tabbar/home-selected.png", name: "美团专送" }, { url: "../../../static/images/tabbar/home-selected.png", name: "跑腿代购" }, { url: "../../../static/images/tabbar/home-selected.png", name: "美食" }, { url: "../../../static/images/tabbar/home-selected.png", name: "城市便利" }, { url: "../../../static/images/tabbar/home-selected.png", name: "美团专送" }, { url: "../../../static/images/tabbar/home-selected.png", name: "跑腿代购" }, ], } }, onLoad() { }, mounted() { // console.log("0"); this.createMenuList(); }, methods: { createMenuList(){ this.menuSwiper = new Array(2); this.menuSwiper[0] = this.menuList; this.menuSwiper[1] = this.menuList; // console.log(this.menuSwiper);
//小长方灰亮的总个数 = 滑动菜单的页数
this.instructData.length = this.menuSwiper.length;
}, //滑块变动事件 changeFun(e){ console.log(e.detail.current); this.num = e.detail.current; } } } </script> <style scoped>/**菜单轮播*/ swiper { height: 320upx !important; } .swiper-item { display: flex; flex-wrap: wrap; align-items: center;/**上下间距居中*/ /* justify-content: space-between; *//**左右间距自动相等排列*/ height: 320upx; } .menu-cont { /* width: calc((100% / 5) -12px) !important; margin: 6px; position: relative; text-align: center; */ /* width: 140upx; */ width: calc((100% / 5) ) !important; text-align: center; } .menu-cont image { width: 70upx; height: 70upx; border-radius: 50upx; display: block; margin: 0 auto; } .menu-cont text{ padding-top: 20upx; font-size: 25upx; } /**菜单轮播下的小长方亮块*/ .instruct-view{ display: flex; /**此div里的元素排成一排*/ justify-content: center; /**并居中显示*/ } .instruct{ width: 30upx; height: 10upx; background: #e6e6e6; margin: 0 10upx; border-radius: 50upx; } .activeclass{ background: #fbae22 !important; } </style>
代码结果:滑动菜单列表,下面灰色的小长方块会跟着变亮背景色
主要代码:view中:class属性的使用
<view class="instruct-view"> <block v-for="(item, index) in instructData" :key="index"> <view class="instruct" :class="[index == num ? 'activeclass':'instruct']" ></view> </block> </view>
。