Vue實現動態樣式的多種方法匯總
<text :style='{color:state?’#ff9933’:’#ff0000’}'>hello world </text><script>export default {data() {return {state: true}}}</script>2. 動態設置class
2.1 主要運用于:實現循環列表中點擊時,相應的元素高亮;(默認首個元素高亮)
<template><div v-for='(item,index) in houseList' :key='index' @click='rightTap(index)'><div :class='{’active’ : index === rightIndex}'>{{item.name}}</div></div></template><script>export default {data() {return {rightIndex:0,houseList:[]};},methods:{rightTap(index){ this.rightIndex = index}}}</script><style lang='scss' scoped>.wrapper{width: 118px;height: 60px;margin: 6px auto 0 auto;.houseTitle{font-size: 22px;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}.active{color:#2a7ffa; background-color: pink;}}</style>
2.2 主要運用于:為特定數值設置相應樣式;
<div : v-for='(item,index) in List' :key='index' @click='clickEvent'> <p>{{item.name}}</p> </div>3. 方法判斷
3.1 主要運用于:為不同的數據值設置相應的樣式;
<template> <div v-for='(item,index) in houseList' :key='index'> <div :style='getStyle(item.status)'>{{item.name}}</div> </div> </template><script>export default { data(){ return{ houseList:[{ id:1, name:1, status:’a’},{ id:2, name:2, status:’b’},{ id:3, name:3, status:’c’} ] } }, methods:{ getStyle(e){ console.log(’值’,e) if(e === ’a’){ return { width:’60px’, height:’60px’, background:’yellow’, margin: ’10px auto’ } }else if(e === ’b’){ return { width:’60px’, height:’60px’, background:’red’, margin: ’10px auto’ } }else if(e === ’c’){ return { width:’60px’, height:’60px’, background:’pink’, margin: ’10px auto’ } } } }}</script>
3.2 主要運用于:在元素多從事件下,顯示相應的樣式;
<template> <div :@click='handleClick(1)' @mousedown='menuOnSelect(1)'> 主頁 </div> </template><script>export default { return { selected: 0, clicked: 0 } methods:{ menuOnSelect(value){ this.selected = value; }, handleClick(value){ this.selected = 0 this.clicked = value } } }</script><style lang='stylus' scoped> .homeWrap.select background red .homeWrap.click background yellow</style>4. 數組綁定
<div :class='[isActive,isSort]'></div>// 數組與三元運算符結合判斷選擇需要的class<div :class='[item.name? ’lg’:’sm’]'></div><div :class='[item.age<18? ’gray’:’’]'></div>// 數組對象結合<div :class='[{ active: isActive }, ’sort’]'></div>data() { return{ isActive:’active’, isSort:’sort’ }}// css.active{ /*這里寫需要設置的第一種樣式*/ } .sort{ /*這里寫需要設置的第二種樣式*/ }5. computed結合es6對象的計算屬性名方法
<div :class='classObject'></div> export default { data(){ return{isActive:true } }, computed:{ classObject() {return{ class_a:this.isActive, class_b:!this.isActive// 這里要結合自身項目情況修改填寫} } } } // css.class_a{ /*這里寫需要設置的第一種樣式*/} .class_b{ /*這里寫需要設置的第二種樣式*/ }
以上就是Vue實現動態樣式的多種方法匯總的詳細內容,更多關于Vue實現動態樣式的資料請關注好吧啦網其它相關文章!
相關文章: