vue中v-for通過動態(tài)綁定class實現(xiàn)觸發(fā)效果
更新時間:2018年12月06日 10:29:47 作者:SilenceJude
這篇文章主要介紹了vue中v-for通過動態(tài)綁定class實現(xiàn)觸發(fā)效果,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
vue動態(tài)綁定class練習。
:class=“{ ‘類名1':條件表達式,‘類名2':條件表達式… }”
<template> <div class="app-*"> <ul> <li v-for="(item,i) of list" :key="i" class="item" @click="clickIndex=i" :class="{'click':i==clickIndex}" ></li> </ul> </div> </template> <script> export default { data() { return { list: [1, 2, 3, 4], clickIndex: -1 }; }, methods: {} }; </script> <style scoped> .item { display: inline-block; width: 100px; height: 100px; cursor: pointer; border: 1px solid black; } .item:hover { background: gray; } .item.click { background: red; } </style>
補充:vue之v-for中給每個item動態(tài)綁定class,動態(tài)添加元素,動態(tài)刪除某個元素的實現(xiàn)
主要解決了在v-for時,如何給每個item添加動態(tài)的樣式,即是說,鼠標滑動到某一項時,可以單獨改變某一項的樣式,同時添加按鈕等操作。以及刪除某一項的操作。
<template> <div class="hello"> <ul> <li v-for="(item, itemIndex) in test" :key="item.id" :class="{defaultClass: itemIndex === isActive}" @mouseenter="onMouseEnter(itemIndex)" @mouseleave="onMouseLeave"> {{ itemIndex+1 }} :{{ item.title }} <button v-if="isActive === itemIndex" @click="deleteItem(itemIndex)">刪除({{itemIndex+1}})</button> </li> </ul> </div> </template>
<script> export default { name: 'HelloWorld', data () { return { test: [ { id: 1, title: 'title first' }, { id: 2, title: 'title second' }, { id: 3, title: 'title third' } ], isActive: '' } }, methods: { onMouseEnter(index) { this.isActive = index }, onMouseLeave() { this.isActive = '' }, deleteItem(index) { this.test.splice(index, 1) } }, computed: { } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { /* display: inline-block; */ margin:10px; } a { color: #42b983; } .defaultClass{ background-color: red; } </style>
總結
以上所述是小編給大家介紹的vue中v-for通過動態(tài)綁定class實現(xiàn)觸發(fā)效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
vue基于v-charts封裝雙向條形圖的實現(xiàn)代碼
這篇文章主要介紹了vue基于v-charts封裝雙向條形圖的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12