vue動態綁定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動態綁定class,動態添加元素,動態刪除某個元素的實現
主要解決了在v-for時,如何給每個item添加動態的樣式,即是說,鼠標滑動到某一項時,可以單獨改變某一項的樣式,同時添加按鈕等操作。以及刪除某一項的操作。
<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通過動態綁定class實現觸發效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答