简体   繁体   中英

strange behavior of vue.js on direct css/style change and removing item from array

Seems that Vue keeps style of a removed item and apply it to the new item with the same index as removed one.

Please check the example below. Item will remove correctly but its style that we changed directly remains for next item. Is this a normal behavior?

I know that we can use v-bind:style or v-bind:class here, that will fix the problem, but sometimes you need to work with a third party library that changes styles directly, in that case we can not use v-bind . Why Vue just doesn't delete the corresponding DOM object that we removed its item from array?

 var init = function() { var app = new Vue({ el: '.app', data: { list: [{val: 1}, {val: 2}, {val: 3}, {val: 4}, {val: 5}], }, methods: { delete_item: function(item) { var index = this.list.indexOf(item); this.list.splice(index, 1); }, }, }); }; var make_it_red = function() { document.querySelectorAll('div span')[2].style.color = 'red'; }; window.onload = init; 
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <div class="app"> <p>First click on make it red button and then try to delete red item.</p> <div v-for="i in list"> <span>item {{i.val}}</span> <button v-on:click="delete_item(i)">delete</button> </div> <button onclick="make_it_red()">make it red</button> </div> 

the issue is that you are not defining a key in your v-for

try with <div v-for="i in list" :key="i" >

though you should use a dedicated id inside an object <div v-for="i in list" :key="i.id" > for best results.

the reason you're seeing this issue is that vue uses keys to identify object, so when there's a change and no key, vue will consider it as same object.

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