这是我使用 Vuejs 的第一个元素。
我已经有了我的主要组件。在我的主要组件中,我有一个数据变量,它是一个数组。例如:
export default {
name: 'example-component',
data() {
return {
options: [
{
text: {
nl: 'Jan',
en: 'John',
},
action: 'x1',
},{
text: {
nl: 'Jansen',
en: 'Doe',
},
action: 'x2',
},
],
}
},
}
在我的模板中 <example-component>
我在另一个组件内使用 v-for 循环。如下图所示:
<my-other-component v-for="option in options" v-on:click.native="select(option.action)"
:key="option.id"></my-other-component>
这似乎工作正常。
<my-other-component>
当它第一次出现在屏幕上时有一个动画。
在 methods
我的部分example-component
有一种方法有时会清空 options
数组并重新填充它,当然,用不同的对象。如果现在运行此方法,前两个选项将没有有此动画,但第三个、第四个、第五个等等会有。
所以看起来这个动画会在 options
中首次创建特定索引时触发。数组。
有谁知道这是为什么以及如何解决这个问题?
PS:我的(相关)CSS:
.option {
animation-timing-function: linear;
animation-name: option;
animation-duration: 2.5s;
}
@-webkit-keyframes option{
0% { opacity: 0; }
75% { opacity: 0; }
100% { opacity: 1; }
}
-
编辑1:
添加animation-iteration-count: infinite
并不能解决问题。它只是重复动画。 (->“选项”每 2.5 秒消失并重新出现)
编辑2:
我试着摆弄了一下。这似乎与时机有关。如果删除操作选项和再次添加它们之间有足够时间,动画似乎工作正常。
另外,我尝试了不同的方法来清空我的数组,IE:
this.options = [];
this.options.length = 0;
this.options.splice(0, this.options.length);
// And all the other goodness
但它们似乎都不影响这个问题。
最佳答案
https://v2.vuejs.org/v2/guide/list.html#Components-and-v-for
In 2.2.0+, when using v-for with a component, a key is now required.
When Vue is updating a list of elements rendered with v-for, it by default uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will simply patch each element in-place and make sure it reflects what should be rendered at that particular index.
To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item.
基本上,如果您没有为循环中的每个数据对象提供唯一的 ID 并将其绑定(bind)到正在循环的元素,Vue 将在数据更改时简单地“修补”数据,并且不会触及 DOM。
关于javascript - CSS 动画仅在首次创建时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309059/