vue動(dòng)態(tài)綁定class練習(xí)。
:class=“{ ‘類名1':條件表達(dá)式,‘類名2':條件表達(dá)式… }”
<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>補(bǔ)充:vue之v-for中給每個(gè)item動(dòng)態(tài)綁定class,動(dòng)態(tài)添加元素,動(dòng)態(tài)刪除某個(gè)元素的實(shí)現(xiàn)
主要解決了在v-for時(shí),如何給每個(gè)item添加動(dòng)態(tài)的樣式,即是說,鼠標(biāo)滑動(dòng)到某一項(xiàng)時(shí),可以單獨(dú)改變某一項(xiàng)的樣式,同時(shí)添加按鈕等操作。以及刪除某一項(xiàng)的操作。
<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>總結(jié)
以上所述是小編給大家介紹的vue中v-for通過動(dòng)態(tài)綁定class實(shí)現(xiàn)觸發(fā)效果,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)錯(cuò)新站長(zhǎng)站網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選