我在 vue 上使用 v-for
和 styles
时遇到问题,看看这个示例,我在 data< 上存储了多个警报错误
,当用户单击关闭按钮时,li
会收到某种样式以将卡片移至左侧,然后我使用 .filter
删除该错误,但是如果要删除的元素是最后一个元素或之前的元素,则样式将转移到下一个元素,使其也消失。
重现步骤: - 运行片段 - 删除第二个警报
const app = new Vue({
el: '#app',
data(){
return {
errors: [
'test',
'blah, blah',
'hey, this is an error message, be careful'
]
}
},
methods: {
dismiss(index) {
const errorElement = this.$refs.errorElements[index]
errorElement.style.height = errorElement.offsetHeight + 'px'
errorElement.style.transition = 'margin-left .2s ease-in, height .2s ease-in .2s, padding .2s ease-in .2s'
errorElement.style.marginLeft = '-250px'
setTimeout(() => {
errorElement.style.height = 0
errorElement.style.padding = 0
}, 200)
setTimeout(() => {
this.errors = this.errors.filter((error, i) => {
return i != index
})
}, 600)
// .2s of margin-left
// .2s of delay to height and padding
// .2s of height and padding
}
}
});
* {
margin: 0;
padding: 0;
outline: 0;
text-decoration: none;
color: inherit;
list-style: none;
box-sizing: border-box;
}
html, body, #app {
height: 100vh;
background-color: #ccc;
font-family: 'Roboto';
}
.alert-wrapper {
position: fixed;
bottom: 25px;
left: 25px;
}
.alert-wrapper ul {
display: flex;
flex-direction: column;
}
.alert-wrapper ul li {
margin-top: 15px;
padding: 15px 25px;
background-color: #e75147;
color: #Fff;
font-size: 12px;
line-height: 140%;
border-radius: 5px;
position: relative;
width: 200px;
}
.alert-wrapper ul li .close {
position: absolute;
top: 5px;
right: 5px;
font-size: 12px;
color: #Fff;
transition: .2s;
cursor: pointer;
opacity: .8;
font-weight: bold;
}
.alert-wrapper ul li .close:hover {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="alert-wrapper">
<ul>
<li v-for="(error, index) in errors" :key="`alert-${index}`" ref="errorElements">
<span class="close" title="Fechar mensagem" @click="dismiss(index)">x</span>
{{ error }}
</li>
</ul>
</div>
</div>
最佳答案
首先,我建议您阅读一下 Vue 的内置过渡。这可以让您避免直接操作 DOM。
但是,这里的主要问题是 key
属性。
当组件首次渲染时,它将创建 3 <li>
键为 alert-0
的元素, alert-1
和alert-2
。从技术上讲,它比这更复杂一些,因为涉及到 VNode,但出于解释目的,我将坚持只使用键和 DOM 节点。
当您删除索引为 1 的项目时,后续项目将沿某个位置随机排列。因此,之前位于索引 2 的项目现在位于索引 1。
当渲染这个更新后的数组时,它将创建 2 <li>
节点,其中一个带有 key
的alert-0
另一个是 alert-1
。然后,Vue 会将新旧节点配对,并制作必要的补丁以从一个节点移动到另一个节点。这就是一切出错的地方。你想要的是 Vue 删除旧的 DOM 节点 alert-1
但就 Vue 而言,它仍然有一个名为 alert-1
的节点。从Vue的 Angular 来看是alert-2
已经消失了。
因此 Vue 将删除节点 alert-2
,不是alert-1
。然后它将更新 alert-1
的内容。 alert-1
的新内容将与 alert-2
的旧内容相同。这可能使它看起来像 style
已经跳转了节点,但实际上并没有,只是内容移动了。
解决方案是使用正确的 key
这与项目本身而不是其索引相关。如果您的情况没有自然选择,那么您可以使用某种形式的随机数或递增计数器在数据中生成合适的 ID。
关于javascript - Vue 在删除 DOM 元素后将内联样式传输到下一个元素 [with snippet],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61514625/