Vue dynamic binding class exercise.
:class="{ 'Class Name 1': conditional expression, 'Class Name 2': conditional expression... }"
<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; } . { background: red; } </style>
Supplement: The implementation of dynamically binding class to each item in v-for, dynamically adding elements, and dynamically deleting an element
It mainly solves how to add dynamic styles to each item in v-for, that is, when the mouse slides to a certain item, you can change the style of a certain item individually, and add buttons and other operations at the same time. and the operation of deleting a certain item.
<template> <div class="hello"> <ul> <li v-for="(item, itemIndex) in test" :key="" :class="{defaultClass: itemIndex === isActive}" @mouseenter="onMouseEnter(itemIndex)" @mouseleave="onMouseLeave"> {{ itemIndex+1 }} :{{ }} <button v-if="isActive === itemIndex" @click="deleteItem(itemIndex)">delete({{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) { = index }, onMouseLeave() { = '' }, deleteItem(index) { (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>
Summarize
The above is what the editor introduced to you. V-for in vue is used to dynamically bind the class to achieve the triggering effect. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!