简体   繁体   English

vue.js在直接更改CSS /样式和从数组中删除项目时的奇怪行为

[英]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. 似乎Vue保留了已删除项目的样式,并将其应用于与已删除项目具有相同索引的新项目。

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 . 我知道我们可以在这里使用v-bind:stylev-bind:class来解决问题,但是有时您需要使用直接更改样式的第三方库,在这种情况下,我们不能使用v-bind Why Vue just doesn't delete the corresponding DOM object that we removed its item from array? 为什么Vue只是不删除我们从数组中删除其项目的相应DOM对象?

 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 问题是您没有在v-for定义键

try with <div v-for="i in list" :key="i" > 尝试<div v-for="i in list" :key="i" >使用<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. 尽管您应该在对象<div v-for="i in list" :key="i.id" >使用专用ID,以获得最佳效果。

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. 您看到此问题的原因是vue使用键来标识对象,因此当发生更改且没有键时,vue会将其视为同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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