通过v-bind
切换样式,:class="{ active:true}"
为true展示样式,false不展示。也可以由:style="{ width:percent + '%'}"
动态控制宽度。
注意后面是JS对象,所以后面的值不可以包含-
,比如background-color
会解析出错,应该写成backgroundColor
,后面的值要有一对''
包裹。
class案例(无样式)
当我们点击某一项时,对应的背景色就会变红。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<style>.active {background-color: red;}
</style><body><div id="app"><ul><li v-for="(item,index) in list" :key="item.id" @click="clickIndex=index" :class="{ active: clickIndex=== index}">{{item.name}}</li></ul></div><script>const app = new Vue({el: '#app',data: {clickIndex: -1,list: [{ id: 1, name: '优惠秒杀' },{ id: 2, name: '特价优惠' }]}})</script>
</body>
</html>
class案例(有样式)
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>* {margin: 0;padding: 0;}ul {display: flex;border-bottom: 2px solid #e01222;padding: 0 10px;}li {width: 100px;height: 50px;line-height: 50px;list-style: none;text-align: center;}li a {display: block;text-decoration: none;font-weight: bold;color: #333333;}li a.active {background-color: #e01222;color: #fff;}</style>
</head><body><div id="app"><ul><li v-for="(item,index) in list" :key="item.id" @click="activeIndex=index"><a :class="{active: activeIndex === index}" href="#">{{item.name}}</a></li></ul></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {activeIndex: 0,list: [{ id: 1, name: '京东秒杀' },{ id: 2, name: '每日特价' },{ id: 3, name: '品类秒杀' }]}})</script>
</body></html>
style案例
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><body><div id="app"><div :style="{ backgroundColor:'red', width:width+'px',height: width+'px'}"></div><button @click="width='200'">200px</button><button @click="width='300'">300px</button></div><script>const app = new Vue({el: "#app",data: {width: '100'}})</script>
</body>
</html>