简体   繁体   中英

Vue JS toggle class on individual items rendered with v-for

I am using the v-for directive to render a list .

<li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." >

  Content

   </li>

What I want is to add a class to the li on which the dragenter event is fired ? How can I accomplish this ? How do I even get a reference to the item (the item,not the data property of the parent component)in the first place inside the event handle?and even If I get the reference how to toggle the class from there? Thanks. I know vue is data-driven , change the data to reflect on the DOM but I would like a concise solution to this rather than index/Id on the data-model based solutions.Thanks

You can access the li being dragged in the dragenter -callback by accessing event.currentTarget (or even event.target would work in this case), where event is the callback's parameter.

 new Vue({ el: '#app', data() { return { grouplist: [ { id: 1, text: 'a' }, { id: 2, text: 'b' }, { id: 3, text: 'c' }, ] } }, methods: { onDragEnter(e) { e.currentTarget.classList.add('drag-enter'); }, onDragLeave(e) { e.currentTarget.classList.remove('drag-enter'); } } }) 
 .drag-enter { background: #eee; } 
 <script src="https://unpkg.com/vue@2.5.16"></script> <div id="app"> <p draggable>Drag this text over the list items below</p> <ul> <li v-for="group in grouplist" :key="group.id" @dragenter="onDragEnter" @dragleave="onDragLeave">{{group.text}}</li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM