您的位置:首页技术文章
文章详情页

利用Vue的v-for和v-bind实现列表颜色切换

【字号: 日期:2023-01-05 18:03:58浏览:2作者:猪猪

需求:

在页面上显示四个列表,初始时字体为黑色。

鼠标点击某一个列表时,该列表的颜色变为红色,其余列表仍为黑色。

代码实现:

<!-- css --><style> .red{ color: red; }</style><!-- html --><div id='app'> <ul> <li v-for='item,index in movies' : v-on:click='change(index)'>{{item}}</li> </ul></div><!-- JavaScript --><script src='https://www.haobala.com/JS/vue.js'></script><script> const app = new Vue({ el: ’#app’, data: { movies: [’肖申克的救赎’,’泰坦尼克号’,’当幸福来敲门’,’流浪地球’], changeRed: -1 }, methods: { change:function (index) { this.changeRed=index; } } })</script>

代码解释:

首先浏览器直接显示列表,因为此时没有监听到click事件。

当鼠标点击某一个列表时,Vue自动获取列表下标,并执行change(index)函数,改变changeRed的值,此时当前列表的v-bind:class='{red: changeRed == index}'中的red为true,当前一项列表显示为红色。其余列表的changeRed == index为false,所以不显示红色。

补充知识:vue学习(绑定class、v-bind:style(对象语法、数组语法))

vue 属性绑定

css

.class0{ color: red; font-size: 10px; } .class00{ color: blue; font-size: 70px; } .class2{ color: yellow; font-size: 30px; } .class3{ color: indianred; } .class4{ font-size: 30px; }

1 class绑定

1.1 字符串绑定

<div id='app1'> 可以绑定一个默认class 字符串绑定class <p :class='a'> xxxx是字符串 </p> <button @click='updates1'> 点击</button></div>

// 1.1 字符串绑定 var a = new Vue({ el:’#app1’, data: { //绑定默认css属性 a: 'class1', b:'class0', }, //动态切换css属性 methods: { updates1 (){ this.a = ’class2’ } } });

1.2 对象绑定 和 数组绑定

<div id='app2'> 对象绑定class <p :class='{class2:isA,class00:isB}'> xxxx是对象 例如 :class='{class2:isA,class00:isB}'</p> <button @click='updates2'> 点击</button> <br> 数组绑定class <br> <p :class='[’class3’,’class4’]'> xxxx是数组 例如 : </p></div>

//1.2 对象绑定 var a = new Vue({ el:’#app2’, data: { //绑定默认css属性 isA: true, isB: false, }, //动态切换css属性 methods: { updates2 (){ this.isA = false; this.isB = true; } } });

图示

利用Vue的v-for和v-bind实现列表颜色切换

点击后

利用Vue的v-for和v-bind实现列表颜色切换

2 style 绑定

<div id='app3'> <div :style='{ color: activeColor, fontSize: fontSize + ’px’ }'>Style 绑定1 例如 :style='{ color: activeColor, fontSize: fontSize + ’px’ }'</div> <div :style='objectCssStyle'>Style 绑定2(绑定到一个样式对象通常更好) 例如 :style='objectCssStyle'</div> <div :style='[clSty1, clSty2]'>Style 绑定3(数组语法) 例如 :style='[activeColor, fontSize]'</div> <button @click='updates4'> 点击</button></div>

// 2 style 绑定 var a = new Vue({ el:’#app3’, data: { //绑定默认css属性 activeColor: ’red’, fontSize: 100, objectCssStyle:{ color: ’red’, fontSize: ’10px’ }, objectCssStyle2:{ color: ’yellow’ }, clSty1: { color: ’green’, fontSize: ’30px’ }, clSty2: { ’font-weight’: ’bold’ } }, //动态切换css属性 methods: { updates4 (){ this.activeColor = 'blue'; this.fontSize = 20; this.objectCssStyle = this.objectCssStyle2 } } });

图示

利用Vue的v-for和v-bind实现列表颜色切换

点击后

利用Vue的v-for和v-bind实现列表颜色切换

以上这篇利用Vue的v-for和v-bind实现列表颜色切换就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Vue
相关文章: